Next: Explanation of the Program
Up: The Code
Here is a code
quadratic.py that calculates roots of a
quadratic according to the method discussed above.
# Compute the real roots of the quadratic equation
# This algorithm does not handle exceptional cases
# Ask the user for a, b, and c and get them
print("Solving the quadratic equation ax^2 + bx + c")
a, b, c = eval(input("Enter a, b, c "))
# Compute the "discriminant"
d = b*b - 4*a*c
# Get the sign of b
signb = 1
if b < 0:
signb = -1
# Avoid loss of significance here by making the sign of the sqrt match
# the sign of b
s = -(b + math.sqrt(d)*signb)/2.
# Use one formula for the first root and the other for the second
x1 = s/a
x2 = c/s
print("Roots are", x1, " ", x2)
Try running the code with an example of your choosing.