例如:http://www.math.cornell.edu/~mec/Winter2009/Luo/Linear%20Congruential%20Generator/linear%20congruential%20gen1.html
我正在尝试为一个示例问题集实现一个LCG,但它对我不起作用,我似乎不知道为什么?
方程为: Xn+1 =(aXn + c) mod m
例如,当X0 =a=c= 7,m= 10时得到的序列是7,6,9,0,7,6,9,0,.
在java中实现这一点,例如-
public static void lcg(){
int a = 7;
int c = 7;
int m = 10;
int x0 = 7;
int N = 10;
for (int x = x0; x < x0+N; x++){
int result = (a*x + c) % m;
System.out.println(result);
}我得到输出:6 3 0 7 4 1 8 5 2 9
而不是预期的7,6,9,0,
我在纸上也是一样的。有人能找出出什么问题了吗?
同样,a=10,c=7,m=11,x0 =3应该给出4,3,4,3的重复模式,但我得到4,3,2,0,10,8,7 6。
发布于 2017-09-18 23:57:20
这似乎只是对迭代的误解。这似乎不是方程的问题,而是你如何处理方程的结果。
我把Xn+1 = (aXn + c) mod m读成
X的下一个值将是
x,+c,modm的当前值“。
注意我的重点。您正在丢弃x (result)的当前值,然后在下一次迭代中使用方程中的“迭代计数器变量”。
将循环更改为
for (int x = x0, i = 0; i < 5; i++) {
// Note x is being updated instead
x = (a*x + c) % m;
System.out.print(x);
}
69076https://stackoverflow.com/questions/46289707
复制相似问题