TITLE: Solving a quadratic equation with precision when using floating point variables
QUESTION [16 upvotes]: I know how to solve a basic quadratic equation with the formula
$$t_{1,2}=\dfrac{-b\pm\sqrt{b^2-4ac}}{2a}$$
but I learned that if $b \approx \sqrt{b^2-4ac}$ floating point precision may give slightly wrong results and this approach is better. It works, indeed. But why? Is there a simple explanation on why this works?

REPLY [3 votes]: As the other comments mention, there is loss of precision when subtracting similar values. So you want to compute one root $r_1$ of $a x^2 + b x + c = 0$ without substraction of possibly similar values and get the other from the relation $r_2 = \frac{c}{a r_1}$. If $4 a c$ is small with respect to $b^2$, $\sqrt{b^2 - 4 a c} \approx b$. So the general strategy is:

If $b < 0$, compute $r_1 = \frac{- b + \sqrt{b^2 - 4 a c}}{2 a}$
If $b > 0$, compute $r_1 = \frac{- b - \sqrt{b^2 - 4 a c}}{2 a}$
If $b = 0$, $r_1 = \sqrt{\frac{c}{a}}$, $r_2 = - \sqrt{\frac{c}{a}}$