Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def get_input(): #gets user values and attempts to convert them to floats for computation
- while True:
- try:
- a = float(input("What is A?: "))
- b = float(input("What is B?: "))
- c = float(input("What is C?: "))
- pass
- except ValueError: #Checks for errors in user input and asks user to re-enter
- print("Not a number, please re-enter")
- else:
- if float(a) == 0: #checks if the user has entered zero for A since you can't divide by zero.
- print ("Can't divide by 0")
- else:
- return (a,b,c)
- 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
- """
- >>> quad_frm(1,2,1)
- (-1.0, -1.0)
- >>> quad_frm(1, 0, 1)
- ((0.0, 1.0), (0.0, -1.0))
- >>> quad_frm(1, -1, -6)
- (3.0, -2.0)
- >>> quad_frm(1,-4,13)
- ((2.0, 3.0), (2.0, -3.0))
- >>> quad_frm(2,-1,-1)
- (1.0, -0.5)
- """
- discrim = (b**2)-(4*a*c) #discriminant (square root(-b^2+4ac))
- two_a = 2*a
- else:
- r1 = (-(b) + ((discrim)**.5))/two_a
- r2 = (-(b) - ((discrim)**.5))/two_a
- #solves for real roots
- return(r1,r2) #returns roots in a tuple
- def print_roots(r1,r2):
- """
- This function checks for real and imaginary roots and formats accordingly,
- all numbers formatted to have two decimal places at max and five characters at max
- """
- if type(r1) == tuple and type(r2) == tuple: #checks if both the inputs consist of tuples
- real_num = str("%5.2f"%(r1[0]))
- r1i = ("%5.2f"%(r1[1]))
- r2i = ("%5.2f"%(r2[1]))
- print ("Root 1 = " + real_num + " +" + str(r1i) + "*i" + " Root 2 = " + real_num + str(r2i) + "*i")
- #prints the roots in the form of a complex number
- else:
- print ("Root 1 = " + "%5.2f"%(r1) + " Root 2 = " + "%5.2f"%(r2)) #prints real roots of inputed values
- def main():
- value = get_input()
- x = quad_frm(value[0],value[1],value[2])
- print_roots(x[0],x[1])
- while True: #reruns code
- if __name__ == "__main__":
- import doctest
- doctest.testmod()
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement