Fastest hypotenuse in javascript?

Phil H picture Phil H · Apr 13, 2012 · Viewed 7.1k times · Source

I've seen a number of questions about simulations and animations in javascript, which often involve calculating the hypotenuse:

hypot = Math.sqrt(x*x + y*y);

Since cartesian coordinates are the weapon of choice in most of these engines, these calculations are needed to find the distance between pairs of points, etc. So any speedup in calculating the hypotenuse could be a great help to many projects.

To that end, can you see a faster method than the simple implementation above? I found an approximation which was marginally faster in Chrome, but turned out to be much slower in Firefox, based on this approximation function in SuperCollider.

Edit 2015-08-15: I've switched the accepted answer to being the Math.hypot one; I suspect the pragmatic approach at present would be to use Math.hypot or a synthesized hypot function if not available, and to compare against the square (per sch's answer) if that is sufficient and Math.hypot is not available.

Answer

sch picture sch · Apr 13, 2012

Often, you don't need to compute the square root and hypot^2 = x*x + y*y is enough. This is the case for example if you want to compare the distances and don't need the actual values.