jan*_*nce 9 javascript math performance approximation
我正在用javascript做一些数字信号处理计算,我发现计算双曲正切(tanh)有点太贵了.这是我目前近似tanh的方式:
function tanh (arg) {
// sinh(number)/cosh(number)
return (Math.exp(arg) - Math.exp(-arg)) / (Math.exp(arg) + Math.exp(-arg));
}
Run Code Online (Sandbox Code Playgroud)
有人知道更快的计算方法吗?
Dav*_*nco 13
从这里开始.
function rational_tanh(x)
{
if( x < -3 )
return -1;
else if( x > 3 )
return 1;
else
return x * ( 27 + x * x ) / ( 27 + 9 * x * x );
}
Run Code Online (Sandbox Code Playgroud)
这是一个合理的功能,以近似一个tanh般的软剪刀.它基于具有调整系数的tanh函数的pade近似.
该函数在x = -3..3范围内,输出范围y = -1..1.超出此范围,输出必须钳位到-1..1.
第一个函数的导数在-3和3处消失,因此向硬裁剪区域的过渡是C2连续的.
Padé逼近的幅度优于泰勒展开.夹紧也可能是一个问题(取决于您的范围).
你可以这样做,并将你的表演时间缩短一半:
function tanh(arg) {
var pos = Math.exp(arg);
var neg = Math.exp(-arg);
return (pos - neg) / (pos + neg);
}
Run Code Online (Sandbox Code Playgroud)