gauravssnl

QuadriaticEquation.py

Apr 5th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. """QuadriaticEquation.py by gauravssnl
  2. script takes quadriatic equation as input and find its root/solutions .Input Example: 1*x^2+4*x^1+4=0 """
  3. _author__ = "gauravssnl"
  4.  
  5. import re
  6. from math import sqrt
  7.  
  8. eqn = raw_input("Equation: ")
  9. pat = re.compile( "([+-]?\d+)\*?x\^2([+-]\d+)\*?x\^1([+-]\d+)=0" )
  10.  
  11. res = pat.match(eqn)
  12. if res :
  13.     # print( res.groups() )
  14.     a,b,c= [eval(x) for x in res.groups() ]
  15.    
  16.     # Discriminant value
  17.     D = b*b-4*a*c
  18.    
  19.     # real roots/solutions
  20.     if D>= 0 :
  21.         x1 = ( -b+sqrt(D) ) / (2*a)
  22.         x2 = ( -b-sqrt(D) ) / (2*a)
  23.    
  24.     #imaginary roots/solutions
  25.     else :
  26.        
  27.         i = sqrt(-D)
  28.         x1 = (-b + eval("%sj"%i)) / (2*a)
  29.         x2 = (-b - eval("%sj"%i)) / (2*a)
  30.    
  31.     print("solutions:")
  32.     print(x1)
  33.     print(x2)
  34.    
  35. else:
  36.     print("Invalid Input")
  37.     print("Input Example: 1*x^2+4*x^1+4=0")
Add Comment
Please, Sign In to add comment