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的答案)进行比较.
很多人都不知道的重点:
hypot = Math.sqrt(x*x + y*y);这在理论上有效,但在实践中可能会失败.如果x太大而x*x溢出,代码将产生无限结果.
以下是如何计算sqrt(x x + y y)而不会有溢出的风险.
Run Code Online (Sandbox Code Playgroud)max = maximum(|x|, |y|) min = minimum(|x|, |y|) r = min / max return max*sqrt(1 + r*r)
参考文献和完整文本:John D. Cook - http://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/
在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。
