3 ms·
This one is fun! However, that particular formula is not my favorite, as it doesn't behave nicely when a is small. The art here is deciding what to special case
by raphlinus 4y ago
This one is fun! However, that particular formula is not my favorite, as it doesn't behave nicely when a is small. The art here is deciding what to special case.
The way I approach this[1] is to choose the sign of the ± to be the same as -b to compute the first root x1. Then the second root is c/(a * x1). There are a few other checks in the code for things overflowing, but that basically gives you very accurate answers across the range.
This is explained a bit in a good Math Exchange post[2]. Jim Blinn's "How to solve a quadratic equation" also makes good reading.
Wait til you get to cubics and quartics.
[1]: https://docs.rs/kurbo/latest/src/kurbo/common.rs.html#116-160 https://docs.rs/kurbo/latest/src/kurbo/common.rs.html#116-16...
[2]: https://math.stackexchange.com/questions/866331/numerically-stable-algorithm-for-solving-the-quadratic-equation-when-a-is-very https://math.stackexchange.com/questions/866331/numerically-...