javascript中最快的斜边?

Phi*_*l H 13 javascript math approximation

我在javascript中看到了很多关于模拟和动画的问题,通常涉及计算斜边:

hypot = Math.sqrt(x*x + y*y);
Run Code Online (Sandbox Code Playgroud)

由于笛卡尔坐标是大多数这些引擎中的首选武器,因此需要进行这些计算以找到点对之间的距离等.因此,计算斜边的任何加速都可能对许多项目有很大帮助.

为此,您能看到比上述简单实现更快的方法吗?我发现Chrome中的近似值稍微快一些,但根据SuperCollider中的近似函数, Firefox中的近似值要慢得多.

编辑2015-08-15:我已将接受的答案改为Math.hypot答案; 我怀疑目前的实用方法是使用Math.hypot或合成的hypot函数(如果不可用),并且如果足够并且Math.hypot不可用则与square(每个sch的答案)进行比较.

sch*_*sch 14

通常,您不需要计算平方根并且hypot^2 = x*x + y*y足够了.例如,如果要比较距离并且不需要实际值,就是这种情况.


Hen*_*nry 6

很多人都不知道的重点:

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

这在理论上有效,但在实践中可能会失败.如果x太大而x*x溢出,代码将产生无限结果.

以下是如何计算sqrt(x x + y y)而不会有溢出的风险.

max = maximum(|x|, |y|)
min = minimum(|x|, |y|)
r = min / max
return max*sqrt(1 + r*r)
Run Code Online (Sandbox Code Playgroud)

参考文献和完整文本:John D. Cook - http://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/


Wal*_*anG 5

在ECMAScript ES6中,您可以使用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))
Run Code Online (Sandbox Code Playgroud)

编辑:您可以在空白选项卡上运行此测试,两种方法都进行了200万次操作,效果非常好,速度提高了24%。

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");
Run Code Online (Sandbox Code Playgroud)

Note:在此测试中,使用了ES6的Math.hypot

在此处输入图片说明

  • “ hypot”在Chrome 62上始终显示较慢。我试图将其设置为严格的功能,以最大程度地减少外部干扰(https://gist.github.com/anonymous/159187ac9a8d3caf97737cd9cf551c1a),但sqrt仍然运行较快。也许他们在某些时候增加了一些防止溢出/下溢的保护措施? (2认同)