我的一个项目需要一个伪随机数生成方案(独立于标准库),我尝试了一个简单的基于LCG的 RNG。它似乎工作正常,只是它在 C++ 和 Python 中产生不同的值。我在下面给出了相关的代码。我无法找到错误。任何帮助将不胜感激!
(c++)
// file: lgc.cc
// compile and run with: g++ lgc.cc -o lgc && ./lgc
#include <cstdio>
#include <cstdint>
#include <vector>
using namespace std;
uint64_t LGC(uint64_t x) {
uint64_t A = 1103515245;
uint64_t C = 12345;
uint64_t M = (1 << 31);
return (A * x + C) % M;
}
int main(int argc, char* argv[]) {
for (auto x : {485288831, 485288832, 10, 16, 255, 756}) {
uint64_t y = LGC(x);
printf("%u %u\n", (uint32_t)x, (uint32_t) y);
}
return 0;
}
(Python)
# file: lgc.py
# run with: python3 lgc.py
def LGC(x):
A = 1103515245;
C = 12345;
M = int(2 ** 31);
return (A * x + C) % M;
for x in [485288831, 485288832, 10, 16, 255, 756]:
y = LGC(x)
print(x, y)
(结果:c++)
485288831 3822790476
485288832 631338425
10 2445230203
16 476387081
255 2223525580
756 1033882141
(结果:蟒蛇)
485288831 1675306828
485288832 631338425
10 297746555
16 476387081
255 76041932
756 1033882141