Fastest hypotenuse in javascript?
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.
An important point that many do not know:
hypot = Math.sqrt(x*x + y*y);
That works in theory, but in practice it may fail. If x is so large that x*x overflows, the code will produce an infinite result.
Here’s how to compute sqrt(xx + yy) without risking overflow.
max = maximum(|x|, |y|) min = minimum(|x|, |y|) r = min / max return max*sqrt(1 + r*r)
Reference and complete text: John D. Cook - http://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/
In ECMAScript ES6 you can use Math.hypot:
// ES5 support
Math.hypot = Math.hypot || function(x, y){ return Math.sqrt(x*x + y*y) }
var x = 3, y = 4;
document.write(Math.hypot(x, y))
Edit: You can run this test on a blank tab, are 2 million operations with both methods, the results are very good, it is 24% faster.
var i, tmp, x = 55, y = 66, end, ini = performance.now();
// Math.sqrt operation
i = 0;
ini = performance.now();
tmp = 0;
while(i++ < 2000000){
tmp += Math.sqrt(x*x + y*y)
}
end = performance.now();
console.log(tmp, "Math.sqrt operation: " + (end - ini) + " ms");
// Math.hypot
i = 0;
ini = performance.now();
tmp = 0;
while(i++ < 2000000){
tmp += Math.hypot(x, y)
}
end = performance.now();
console.log(tmp, "Math.hypot: " + (end - ini) + " ms");
Note: In this test, it's used ES6's Math.hypot.