IT_Programming/JavaScript

가우시안 (정규분포) 난수 생성 예제

JJun ™ 2010. 12. 14. 15:10

[ 가우시안(정규분포) 난수 생성 예제 ]

 

/*
* Returns member of set with a given mean and standard deviation
* mean: mean
* standard deviation: std_dev
*/
function createMemberInNormalDistribution(mean,std_dev){
    return mean + (gaussRandom()*std_dev);
}

/*
* Returns random number in normal distribution centering on 0.
* ~95% of numbers returned should fall between -2 and 2
*/
function gaussRandom()

{
    var u = 2*Math.random()-1;
    var v = 2*Math.random()-1;
    var r = u*u + v*v;
   
/*if outside interval [0,1] start over*/
    if(r == 0 || r > 1) return gaussRandom();

    var c = Math.sqrt(-2*Math.log(r)/r);
    return u*c;

   /* todo: optimize this algorithm by caching (v*c)
     * and returning next time gaussRandom() is called.
     * left out for simplicity */
}


-------------------------------------------------------------------------------------------------

 

 

[ 가우스 역분포 구하는 예제 소스 코드 ]

 

public double inverseGaussian(double mu, double lambda)

{
       Random rand = new Random();

      

       // sample from a normal distribution with a mean of 0 and 1 standard deviation
       double v = rand.nextGaussian();   
       double y = v*v;
       double x = mu + (mu*mu*y)/(2*lambda) - (mu/(2*lambda)) * Math.sqrt(4*mu*lambda*y

                        + mu*mu*y*y);

       double test = rand.nextDouble();  // sample from a uniform distribution between 0 and 1
       if (test <= (mu)/(mu + x)) {
              return x;

       } else {
              return (mu*mu)/x;

       }
}