1

I wrote the quadratic formula to compute two roots (including complex root) and it works just fine. However, when I try to plugin the two roots back to the formula to verify they indeed make the quadratic equation equals to zero, it fails. It gives -4.440892098500626e-16+0j instead of 0. How can I fix this?

Originally I tried to use delta ** 0.5 and it made my two roots to 0.9999999 instead of 1, then I used cmath and fixed the problem, but it did not fix the problem described above.

def quadraticFormula(a, b, c):

delta = b**2 - 4 * a * c
x1 = (-b + cmath.sqrt(delta)) / (2 * a)
x2 = (-b - cmath.sqrt(delta)) / (2 * a)

for x in x1, x2:
    y = a * x**2 + b * x + c
    print(y==0)
    print(y)
return x1, x2

print(quadraticFormula(1, 2, 3))

would expect to print out True, True, 0, 0, and the two roots. Actual results: False, False, -4.440892098500626e-16+0j, -4.440892098500626e-16+0j, ((-1+1.4142135623730951j), (-1-1.4142135623730951j))

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

0 Answers0