In Firefox Math.hypot(x, y)
gives the same result as Math.sqrt(x*x, y*y)
That lets us make a fairly confident guess for how Firefox implemented Math.hypot
:-)
in Chrome the result from Math.hypot(x, y)
is slightly different
Here is Chrome's implementation:
https://chromium.googlesource.com/v8/v8/+/master/src/builtins/math.tq#389
As you can see from the comment in line 421, a Kahan summation is used to avoid/minimize rounding errors -- so apparently the intention was to be more accurate than a simple sqrt(x*x + y*y)
implementation. (I've tried to verify whether that's actually the outcome in this case, but Wolfram Alpha just rounds to 56.1124
, and I don't know of another convenient infinite-precision floating-point evaluator out there, so I can't say for sure.)
doing the calculation correctly
In the presence of limited precision and rounding errors, the "correct" way is hard to define. For example, there are situations where the (mathematically equivalent!) expressions (a * b) / c
and a * (b / c)
produce different results due to rounding, and what's more, where the values of a, b, c determine which way of computing the result gets closer to the (unlimited-precision) theoretical result, so each implementation could get "lucky" or "unlucky".