0
import java.io.*;

public class TestCaseAbcd {
    public static void main(String args[]) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader stdin = new BufferedReader(
        float x0;
        float a, c, mod;
        int num, ch = 0;
        double[] rNumbers;
        double[] rTemp;

        System.out.println("Enter the SEED value: ");
        System.out.println("x0 ");
        x0 = Float.parseFloat(stdin.readLine());

        System.out.println("Enter the multiplier's value:");
        System.out.println("a: ");
        a = Float.parseFloat(stdin.readLine());

        System.out.println("Enter the value of increment c and modulus m: ");
        System.out.println("c: ");
        c = Float.parseFloat(stdin.readLine());

        System.out.println("m: ");
        mod = Integer.parseInt(stdin.readLine());

        System.out.println("How many random nunbers u need? ");
        num = Integer.parseInt(stdin.readLine());

        rNUmbers = new double[num];              
        rTemp = new double[rNumbers.length];
        rTemp[0] = x0;

        for (int i = 0; i < num; i++) 
        {
            if(i + 1 != num)
            {
                rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
            }
            else
            {
                break;
            }
        }
        for (int i = 0; i < rNumbers.length; i++) 
        {
            if (i + 1 != num) 
            {
                rNumbers[i] = rTemp[i] / mod;
            } 
            else 
            {
                break;
            }
        }

        System.out.println("The PSEUDO random numbers are: ");
        for (int i = 0; i < rNumbers.length; i++) 
        {
            System.out.println(rNumbers[i]);
        }

        double firstNum = rNumbers[0];

        System.out.println("1. Select Mutant 1 ");
        System.out.println("2. Select Mutant 2 ");
        System.out.println("3. Exit ");
    }
}

在上面的代码中,预期的输出应该从: 开始0.68。但是,它开始于: 0.37。事实上,即使我更改了以下代码:

 rTemp[i+1] = ( ( (rTemp[i]*a) + c ) % mod);

到:

 rTemp[i+1] = ( ( (rTemp[i]/a) + c ) % mod);

输出仍然从 0.37 开始。输入值为:

x0 = 37
a = 7
c = 9
m = 100

请帮助我分析代码,以免输出以0.37.

问题摘要:代码产生相同的数字,即0.37无论代码中上述等式被修改为什么。

4

1 回答 1

0

您将第一个值设置rTemp37,然后从第一个值开始打印。只有打印的第一个值是0.37.

x0 = 37
mod = 100
...
rTemp[0] = x0;
...
rNumbers[i] = rTemp[i] / mod;
...
System.out.println(rNumbers[i]);

要实现您正在寻找的输出,请更改此:

rTemp[0] = x0;

for (int i = 0; i < num; i++) 
{
    if(i + 1 != num)
    {
        rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
    }
    else
    {
        break;
    }
}

对此:

rTemp[0] = (((x0 * a) + c) % mod);

for (int i = 0; i < num-1; i++) 
{
    rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}

附带说明一下,如果您真正想要的是一个伪随机双精度数组,那么执行以下操作会更容易:

Random rnd = new Random(seed);
double[] rNumbers = new double[num];
for(int i = 0; i < num; i++)
    rNumbers[i] = (double)rnd.nextInt(100) / 100;

对于任何给定的种子,您每次都会得到相同的双精度数组。

于 2013-08-12T15:59:52.490 回答