Stable alternative to the quadratic formula¶
We repeat the rootfinding experiment of Instability of the quadratic formula with an alternative algorithm.
a = 1; b = -(1e6+1e-6); c = 1;
First, we find the “good” root using the quadratic formula.
@show x1 = (-b + sqrt(b^2-4*a*c)) / (2*a);
x1 = (-b + sqrt(b ^ 2 - 4 * a * c)) / (2a) = 1.0e6
Then we use the alternative formula for computing the smaller root:
@show x2 = c/(a*x1);
x2 = c / (a * x1) = 1.0e-6
As you see in this output, Julia often suppresses trailing zeros in a decimal expansion. To be sure we have an accurate result, we compute its relative error.
abs(x2-1e-6) / 1e-6
0.0