如何从Gaussian(0,1)改进我的Java代码进行仿真

时间:2017-07-14 11:35:29

标签: java simulation gaussian inversion

我是java的新手,我创建了一个代码,用于通过反演方法从高斯分布模拟100000个观测值,均值= 0,标准差= 1。与在R中使用rnorm命令或在Python中使用numpy.random进行模拟相比,代码很慢,好吧我知道我在代码中使用了很多for循环,但不是在R的核心中使用循环和Python命令进行随机模拟?无论如何这里是我的代码,如果你对如何改进它有任何建议请分享(类名是'HelloWorld',因为我打印了昨天用java开始的'Hello World'消息)。

我的代码:

import java.io.*;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class HelloWorld {

public static void main(String[] args) 
{
    double randomNum=0.0;
    for(int i=0;i<99999;i++) {
      //technically generating from uniform (0,1)
      randomNum=ThreadLocalRandom.current().nextDouble(0, 1); 
      System.out.println(nr(0,randomNum));}
}



public static double gaussian01(double x){ 
    //defining the gaussian (0,1)
     double par=(Math.sqrt(2*Math.PI));
     double ar=(Math.exp(-(x*x)/2));
     return ar/par;}

public static double integx2(double upper){  
// defining the integration for the gaussian function
      double lower=-9;
      double step= 0.001;
      int ran=(int)((upper-lower)/step);
      double[] xs=new double[ran+1];
      xs[0]=lower;
      for(int i=1; i<=ran;i++) xs[i]=xs[i-1]+step;
      double[] gin= new double[ran+1];
      for(int i=0; i<=ran;i++) gin[i]=step*(gaussian01(xs[i]));
      double sum=0;
      for(int i=0; i<=ran;i++) sum=sum+gin[i];
      return sum;}   


public static double fun(double upper1,double u){ 
//defining the equation which's solution follows the gaussian (0,1) if 'u' is taken from Uniform(0,1) 
      return integx2(upper1)-u;}


public static double grad(double x0, double uu){ 
  // computing the first derivative for the newton-raphson
   return (fun(x0+0.01,uu)-fun(x0,uu))/0.01;}

public static double nr(double str, double uuu1){ 
    // solving the equation above with the newton raphson method
     double x1=str-fun(str,uuu1)/grad(str,uuu1);
     double dif=x1-str;
     while(Math.abs(dif)>=0.001){
            str=x1;
            x1=str-fun(str,uuu1)/grad(str,uuu1);
            dif=x1-str;}
     return x1;}


}

0 个答案:

没有答案