【发布时间】:2021-01-27 14:49:21
【问题描述】:
我创建了一个线性同余生成器 (LCG),但它似乎给了我错误的输出。
// Instance variables
private long currentRandomNumber;
private long a;
private long c;
private long m;
public static void main(String[] args) {
// perform calculations and tests here
final long seed = 99L;
// Java's java.util.Random class values (according to Wikipedia):
long a = 25214903917L;
long c = 11L;
long m = 2^48L;
LCG lcg = new LCG(a, c, m, seed);
System.out.println("Sequence of LCG class: " + lcg.nextRandom() + ", " + lcg.nextRandom() + ", " + lcg.nextRandom() + ", " + lcg.nextRandom() + ", " + lcg.nextRandom());
}
public LCG(long seed, long a, long c, long m) {
currentRandomNumber = seed;
this.a = a;
this.c = c;
this.m = m;
}
// Implementation of the recurrence relation of the generator
public long nextRandom() {
currentRandomNumber = (a * currentRandomNumber + c) % m;
return currentRandomNumber;
}
我得到的输出是:
Sequence of LCG class: 28, 61, 28, 61, 28
我使用 a、c 和 m 的这些值是因为我读到 java.util.Random 类也使用这些值。但是使用具有相同种子的此类会给出不同的答案。我还检查了其他 lcg 计算器,我的答案也不匹配。我不知道出了什么问题。
【问题讨论】:
-
调用构造函数的方式与定义的方式不同(“a, c, m, seed” vs. “long seed, long a, long c, long m”)
-
2^48是可疑的。你为什么不直接输入50? -
谢谢,但在我匹配订单后,我仍然得到错误的输出。现在我得到 44、9、14、49、44
-
请接受答案或发表评论以拒绝。