Advertisement
alex26033

quadratic formula alex gonzalez code

Mar 18th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | None | 0 0
  1. def get_input():  #gets user values and attempts to convert them to floats for computation
  2.     while True:
  3.         try:
  4.             a = float(input("What is A?: "))
  5.             b = float(input("What is B?: "))
  6.             c = float(input("What is C?: "))
  7.             pass
  8.         except ValueError:  #Checks for errors in user input and asks user to re-enter
  9.             print("Not a number, please re-enter")
  10.         else:
  11.             if float(a) == 0:  #checks if the user has entered zero for A since you can't divide by zero.
  12.                 print ("Can't divide by 0")
  13.             else:
  14.                 return (a,b,c)
  15.    
  16. def quad_frm(a,b,c): #takes the inputed values of a, b, and c and solves for roots both imaginary and real and checks answers using a doctest
  17.     """
  18.    >>> quad_frm(1,2,1)
  19.    (-1.0, -1.0)
  20.  
  21.    >>> quad_frm(1, 0, 1)
  22.    ((0.0, 1.0), (0.0, -1.0))
  23.  
  24.    >>> quad_frm(1, -1, -6)
  25.    (3.0, -2.0)
  26.    
  27.    >>> quad_frm(1,-4,13)
  28.    ((2.0, 3.0), (2.0, -3.0))
  29.  
  30.    >>> quad_frm(2,-1,-1)
  31.    (1.0, -0.5)
  32.    """
  33.    
  34.     discrim = (b**2)-(4*a*c) #discriminant (square root(-b^2+4ac))
  35.     two_a = 2*a
  36.  
  37.     else:
  38.         r1 = (-(b) + ((discrim)**.5))/two_a
  39.         r2 = (-(b) - ((discrim)**.5))/two_a
  40.         #solves for real roots
  41.         return(r1,r2) #returns roots in a tuple
  42.  
  43. def print_roots(r1,r2):
  44.     """
  45.    This function checks for real and imaginary roots and formats accordingly,
  46.    all numbers formatted to have two decimal places at max and five characters at max
  47.    """
  48.     if type(r1) == tuple and type(r2) == tuple: #checks if both the inputs consist of tuples
  49.         real_num = str("%5.2f"%(r1[0]))
  50.         r1i = ("%5.2f"%(r1[1]))
  51.         r2i = ("%5.2f"%(r2[1]))
  52.         print ("Root 1 = " + real_num + " +" + str(r1i) + "*i" + " Root 2 = " + real_num + str(r2i) + "*i")
  53.         #prints the roots in the form of a complex number
  54.     else:
  55.         print ("Root 1 = " + "%5.2f"%(r1) + " Root 2 = " + "%5.2f"%(r2)) #prints real roots of inputed values
  56.        
  57. def main():
  58.     value = get_input()
  59.     x = quad_frm(value[0],value[1],value[2])
  60.     print_roots(x[0],x[1])    
  61.  
  62. while True: #reruns code
  63.     if __name__ == "__main__":
  64.         import doctest
  65.         doctest.testmod()
  66.         main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement