高斯随机分布的 NaN 误差

NaN error for gaussian random distribution

我在输出之间得到随机的 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?

在你的代码中 dRandom1 可以是负数,而实对数只接受来自 (0, +inf)

的参数