Suppose we want to calculate $\sqrt{a^2+b^2}-|a|$ in MatLab. Using sqrt(a^2 + b^2) - abs(a) will have some problems:
- If
aorbare too large, it may cause overflow - if
aandbare too small, it may cause underflow - if
a>>b,a^2 + b^2may be equal toa^2in machine
What's a more stable algorithm to calculate this without leading to overflow, underflow or omitting b^2?
First thing that came to my mind was to use if clauses that if one error is going to happen, then stop. But I think there can be a way to calculate the answer anyway, because we don't need a^2 or b^2, we need sqrt(a^2 + b^2) - abs(a). But I couldn't find a way to do the calculation when for example b is too large. Second thing that came to my mind was to change the formula. I only could reach sqrt((a + b)^2 - 2*a*b) - abs(a) and couldn't expand the formula anymore. This would help in 3rd problem case, but won't help overflow or underflow I think. Any help is so much appreciated!
hypot(a, b)as I have some limits at the moment. But It'll be really useful to me in the future. Thanks again. – Ferran Gonzalez Oct 31 '23 at 14:00hypotin any way. That's just his suggestion to avoid overflows. If you want, you can actually copy the implementation ofhypotfrom an (appropriately-licensed) open source language into your own code since the implementation is quite simple. Alternatively, you can also use a cases based solution and approximations as in @WolfgangBangerth's good answer. – Aravindh Krishnamoorthy Oct 31 '23 at 14:42