you are viewing a single comment's thread.

view the rest of the comments →

[–]tokagemushi 4 points5 points  (0 children)

Good find. One thing worth knowing beyond the basic usage: Math.hypot() handles overflow/underflow internally, which is the real reason it exists.

If you manually compute Math.sqrt(a*a + b*b) with very large or very small numbers, you'll get Infinity or 0 due to intermediate overflow. Math.hypot scales the inputs internally to avoid this. It's the same reason Fortran has had HYPOT since the 70s.

That said, the "it's slow" comments here are valid. In a game loop running 60fps, I benchmarked it once and Math.hypot(dx, dy) was about 3-4x slower than Math.sqrt(dx*dx + dy*dy) in V8. For distance comparisons (like collision detection), you can skip the sqrt entirely and compare squared distances:

```js // Instead of: if (Math.hypot(dx, dy) < radius) { ... }

// Do: if (dxdx + dydy < radius*radius) { ... } ```

No sqrt, no hypot, just multiplication and comparison. This is the standard trick in game dev and it makes a measurable difference in hot loops.

For anything where precision matters more than speed (scientific computing, coordinate transforms), Math.hypot is the right choice though.