高斯随机分布的NaN误差

时间:2015-02-20 23:30:30

标签: java random distribution nan gaussian

我在输出之间得到随机NaN。

Random Temp:61.816288952756864 'F
Random Temp:NaN 'F
Random Temp:NaN 'F
Random Temp:63.674960517071916 'F
Random Temp:NaN 'F
Random Temp:62.581425292320894 'F
Random Temp:58.21928355494033 'F
Random Temp:60.00714587886456 'F
Random Temp:NaN 'F
Random Temp:60.62983167247955 'F
Random Temp:62.74961457200155 'F
Random Temp:58.50731966210792 'F
Random Temp:NaN 'F
Random Temp:55.20026299393227 'F

这是我的代码:

public static double gaussRandom(double dAverage, double dStddev, Random timeRand){
    double iRandom1, iRandom2;
    double dRandom1, dRandom2, result;

    //iRandom1 = timeRand.nextInt();
    //dRandom1 = (double)iRandom1 /2147483647;
    //iRandom2 = timeRand.nextInt();
    //dRandom2 = (double)iRandom2 /2147483647;

    iRandom1 = timeRand.nextInt();
    dRandom1 = (double)iRandom1 /2147483647.0;
    iRandom2 = timeRand.nextInt();
    dRandom2 = (double)iRandom2 /2147483647.0;

    result = dAverage + dStddev * Math.sqrt(-2.0* Math.log(dRandom1))*Math.cos(6.28318531*dRandom2);

    return result;
}

public static void main(String [] args){

    int i, liSampleSize;
    double dAverage, dStddev, result;

    System.out.println("==========================\n");
    System.out.println("Gaussian numbers generator\n");
    System.out.println("==========================\n");

    liSampleSize = 24*4; // 24 hours every 15 mins;
    dAverage = 60; //Average temp;
    dStddev = 2; //standard deviation of 20;

    Random myRand = new Random();
    myRand.setSeed(System.currentTimeMillis());

    for(i = 0; i<liSampleSize;i++)
    {
        result = gaussRandom(dAverage,dStddev,myRand);
        System.out.println("Random Temp:"+ result +" 'F");
    }


}

如何修复此代码,以便它不会生成NaN?

1 个答案:

答案 0 :(得分:1)

在您的代码dRandom1中可能是否定的,而真正的对数只接受来自(0, +inf)的参数