无法获得自然对数公式

时间:2018-03-28 22:47:57

标签: java probability

我试图让我的程序输出这个公式的前500个值:-12 * ln(1-x)其中x是double next()的返回值。我不知道自己做错了什么,因为我无法获得正确的输出。随机数使用该公式x(i + 1)=(a * x(i)+ c)mod k

public class myRnd {
    // Linear values for x(i+1) = (a * x(i) + c) % k 
    final static int a = 7893;
    final static int c = 3517;
    final static int k = 8192;

    // Current value for returning
    int x;
    int y;
    int z;

    public myRnd() {
        // Constructor simply sets value to half of k
        x = (125*k) /1024;
        //y = (125*k) /1024;
    }

    double next() {
        // Calculate next value in sequence 
        x = (a * x + c) % k; 

        // Return its 0 to 1 value 
        return (double)x / k;
    }

    public static void main(String[] args) {
        int situation;
        double sec_answer;
        // Create a new myRnd instance
        myRnd r = new myRnd();
        // Output 53 random numbers from it     
        for (int i = 0; i < 53; i++) {
            System.out.println (r.next());
        }
        System.out.println("random variable");
        for(int b = 0; b < 500; b++){
            sec_answer = (-12)*Math.log(1- r.next());
            System.out.println(sec_answer);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

我想这些是你在每个循环中期望从程序中获得的前5个值!

0.9302978515625
0.270263671875
0.6204833984375
0.90478515625
0.8985595703125

random variable
31.962289651479345
3.78086405322487
11.626283246646423
28.21943313114782
27.45940262908609

main方法中,您只有一个类实例:

// Create a new myRnd instance
myRnd r = new myRnd();

此初始化将传播到for个循环。

简单解决方案:为第二个myRnd循环添加for的另一个实例/初始化,例如,您可以在第二个循环之前重用与r = new myRnd();相同的变量。