开发者

Gauss error function implementation for JavaScript

开发者 https://www.devze.com 2022-12-13 21:21 出处:网络
Is there a free (BSD- or开发者_如何学JAVA MIT-licensed) Gauss error function implementation written in JavaScript?I did some research on Gaussian approximation.

Is there a free (BSD- or开发者_如何学JAVA MIT-licensed) Gauss error function implementation written in JavaScript?


I did some research on Gaussian approximation. My best found in accuracy/performance is :

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

This trick may seem ugly but it give your a null average and sigma²=1/2 as expected.

I hope this will help.


Here is the code, using the approximation from wikipedia as described in Peter Mortensen's response Original credit goes to 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;
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消