Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- def get_coeff():
- """
- function displays a prompt to the user and guarantees the returned
- value is float.
- :
- This function takes input from the user and utilizes
- exception handling to make sure that the user only inputs numbers.
- :
- """
- while True:
- try:
- a = float(input("a: "))
- b = float(input("b: "))
- c = float(input("c: "))
- return (a,b,c)
- except ValueError:
- print ("Please only enter a numebr")
- else:
- if float(a) == 0:
- print ("You cannot divide by zero")
- def quad_frm(a,b,c):
- """
- given the coefficients for a quadratic equation, returns the roots, either
- real or imaginary, as a tuple of values.
- :
- :
- This code starts by intializing variables of the quadratic formula to be more legible for the reader.
- It sets the discriminant as well as the denominator to avoid repitition.
- Then it checks whether the discriminant is negative or positive to establish whether the roots are real or complex.
- Lastly, it returns the complex roots in a tuple of tuples and the real roots as just a singular tuple.
- BEGIN DOCTESTS
- >>> 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)
- """
- discriminant = (b**2)-(4*a*c)
- denominator = 2 * a
- if discriminant < 0:
- complexRoot1 = ((discriminant/-1)**.5)/(denominator)
- complexRoot2 = -((discriminant/-1)**.5)/(denominator)
- b = (b*(-1))/(denominator)
- return((b,complexRoot1),(b,complexRoot2))
- else:
- rOne = (-(b) + ((discriminant)**.5))/denominator
- rTwo = (-(b) - ((discriminant)**.5))/denominator
- return(rOne,rTwo)
- def print_roots(rOne,rTwo):
- """
- This function checks for real and imaginary roots and formats accordingly,
- all numbers formatted to round for three decimals.
- """
- if type(rOne) == tuple and type(rTwo) == tuple:
- realNumber = round(rOne[0],3)
- rOneComplex = round(rOne[1],3)
- rTwoComplex = round(rTwo[1],3)
- print ("r1: " + str(realNumber) + " +" + str(rOneComplex) + "*i" " r2: " + str(realNumber) + str(rTwoComplex) + "*i")
- else:
- print ("r1: " + str(round(rOne , 3)) + " r2: " + str(round(rTwo, 3)))
- def main():
- value = get_coeff()
- x = quad_frm(value[0],value[1],value[2])
- print_roots(x[0],x[1])
- if __name__ == "__main__":
- import doctest
- doctest.testmod()
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement