我的线性同余生成器有一个问题。我有两个模数。如果我替换或删除其中任何一个,除了在最后启动的计数器之外,我不会得到任何输出,但如果没有要使用计数器处理的输出,它就毫无用处。
我需要应用程序输出 0 到 9 范围内的数字,然后在最后输出数字的分布。这是我的代码:
public static void main(String[] args) {
int fact;
int constant;
int modulus;
int seed;
Scanner scan = new Scanner(System.in);
System.out.println("Input fact: ");
fact = scan.nextInt();
System.out.println("Input constant: ");
constant = scan.nextInt();
System.out.println("Input modulus: ");
modulus = scan.nextInt();
System.out.println("Input seed: ");
seed = scan.nextInt();
int[] arrayBox;
arrayBox = new int[10];
for (int i = 0; i < 10; i++) {
seed = (seed * fact + constant) % modulus; // First modulus
System.out.println(seed);
arrayBox[seed % 10] = arrayBox[seed % 10] + 1; // Second modulus
}
for (int i = 0; i < 10; i++) {
System.out.print(+(100 * arrayBox[i] / 10) + "% ");
}
}
有没有什么办法绕过第二个模数,并且仍然让我的输出和计数器在我想要的范围内工作(0 到 9)?
最佳答案
我在理解您想要做的事情时遇到了一些麻烦,但我认为您最终想要的是:
System.out.println(i + ":\t" + (100*arrayBox[i]/10) + "%");
请注意,此程序不会在任何地方保存实际的 seed
值,因此您将无法查看它们。
下面是这个程序的运行示例,其中输入参数有一些合理的值:
Input fact:
257
Input constant:
31
Input modulus:
64
Input seed:
89
56
23
54
21
52
19
50
17
48
15
0: 10%
1: 10%
2: 10%
3: 10%
4: 10%
5: 10%
6: 10%
7: 10%
8: 10%
9: 10%
关于java - 如何修复线性同余生成器中的模数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32142051/