java实现标准正态分布

[java]  view plain copy
  1. import java.util.*;  
  2. public class zheng0_1 {  
  3.     public static void main(String[] args) {  
  4.         double zhengtai0_1;  
  5.         java.util.Random r = new java.util.Random();  
  6.           
  7.           
  8.         for(int i=0;i<20; i++) {  
  9.             zhengtai0_1 = r.nextGaussian();  
  10.             System.out.println(zhengtai0_1);              
  11.         }  
  12.           
  13.     }  
  14. }  
 

 

Java内部实现:标准正态分布。即:Polar Method方法

public double nextDouble() {

        return (((long)(next(26)) << 27) + next(27))

        / (double)(1L << 53);

}

 

    private double nextNextGaussian;

private boolean haveNextNextGaussian = false;

 

synchronized public double nextGaussian() {

        // See Knuth, ACP, Section 3.4.1 Algorithm C.

        if (haveNextNextGaussian) {

        haveNextNextGaussian = false;

        return nextNextGaussian;

    } else {

            double v1, v2, s;

        do {

                v1 = 2 * nextDouble() - 1; // between -1 and 1

              v2 = 2 * nextDouble() - 1; // between -1 and 1

                s = v1 * v1 + v2 * v2;

         } while (s >= 1 || s == 0);

        double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);

        nextNextGaussian = v2 * multiplier;

        haveNextNextGaussian = true;

        return v1 * multiplier;

        }

    }

你可能感兴趣的:(java实现标准正态分布)