'Why do I get an infinity error when calculating roots using the quadratic formula in python?
I am using python to solve the quadratic formula using two different equivalent mathematical equations. Using the formula -b +- sqrt(b^2-4ac)/2a I get results that match wolfram alpha. But when I use an equivalent formula 2c/(-b -+ sqrt(b^2-4ac) I will get an infinity error. Why does this happen in python?
import numpy as np
a,b,c = 1.2*10**(-17), 5.5, 10**(-4)
x = (-b+np.sqrt(b**2-4*a*c))/(2*a)
print(x)
x = (-b-np.sqrt(b**2-4*a*c))/(2*a)
print(x)
x = 2*c/(-b - np.sqrt(b**2 - 4*a*c))
print(x)
x = 2*c/(-b + np.sqrt(b**2 - 4*a*c))
print(x)
0.0
-4.583333333333333e+17
-1.8181818181818182e-05
inf
Solution 1:[1]
If you want to remove any machine accuracy error, I find that by expanding the quadratic formula in both cases using the taylor series expansion will give you the correct answer regardless of the values of a,b, and c for the quadratic formula.
a,b,c = 1.2*10**(-17), 5.5, 10**(-4)
x = 2*c/(-b + b-2*a*c/b)
print(x)
x = 2*c/(-b-b-2*a*c/b)
print(x)
x = (-b -b -2*a*c/b)/(2*a)
print(x)
x = (-b + b - 2*a*c/b)/(2*a)
print(x)
-4.583333333333333e+17
-1.8181818181818182e-05
-4.583333333333333e+17
-1.8181818181818182e-05
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Logan |
