JavaScript的高斯错误函数实现

时间:2009-12-15 08:53:34

标签: javascript

是否有用Gauss error function编写的免费(BSD或MIT许可)JavaScript实现?

2 个答案:

答案 0 :(得分:12)

我对高斯近似做了一些研究。 我在准确性/性能方面的最佳表现是:

var gaussrand =(Math.random()+ Math.random()+ Math.random()+ Math.random()+ Math.random()+ Math.random() - 3);

这个技巧可能看起来很难看,但它会给你一个平均值和sigma²= 1/2的预期值。

我希望这会有所帮助。

答案 1 :(得分:4)

以下是代码,使用Peter Mortensen的回复中描述的approximation from wikipedia 最初的信用额度为Abramowitz and Stegun

        function erf(x) {
            var z;
            const ERF_A = 0.147; 
            var the_sign_of_x;
            if(0==x) {
                the_sign_of_x = 0;
                return 0;
            } else if(x>0){
                the_sign_of_x = 1;
            } else {
                the_sign_of_x = -1;
            }

            var one_plus_axsqrd = 1 + ERF_A * x * x;
            var four_ovr_pi_etc = 4/Math.PI + ERF_A * x * x;
            var ratio = four_ovr_pi_etc / one_plus_axsqrd;
            ratio *= x * -x;
            var expofun = Math.exp(ratio);
            var radical = Math.sqrt(1-expofun);
            z = radical * the_sign_of_x;
            return z;
        }
相关问题