用C和Python编写的相同XorShift函数会产生不同的结果。你能解释一下吗?
XorShift函数以下列方式生成数字:
x(0) = 123456789
y(0) = 362436069
z(0) = 521288629
w(0) = 88675123
x(n+1) = y(n)
y(n+1) = z(n)
z(n+1) = w(n)
w(n+1) = w(n) ^ (w(n)>>19) ^ (x(n)^(x(n)<<11)) ^ ((x(n)^(x(n)<<11)) >> 8)
我在Python中编写了这个函数来生成w:
的后续值X = 123456789
Y = 362436069
Z = 521288629
W = 88675123
def xor_shift():
global X, Y, Z, W
t = X ^ (X << 11)
X = Y
Y = Z
Z = W
W = W ^ (W >> 19) ^ t ^ (t >> 8)
return W
W1 = xor_shift() # 252977563114
W2 = xor_shift() # 646616338854
W3 = xor_shift() # 476657867818
用C编写的相同代码(可以在维基百科http://en.wikipedia.org/wiki/Xorshift上找到)给出了不同的结果:
#include <stdint.h>
uint32_t xor128(void) {
static uint32_t x = 123456789;
static uint32_t y = 362436069;
static uint32_t z = 521288629;
static uint32_t w = 88675123;
uint32_t t;
t = x ^ (x << 11);
x = y; y = z; z = w;
return w = w ^ (w >> 19) ^ t ^ (t >> 8);
}
cout << xor128() <<'\n'; // result W1 = 3701687786
cout << xor128() <<'\n'; // result W2 = 458299110
cout << xor128() <<'\n'; // result W3 = 2500872618
我认为我的Python代码或使用cout存在问题(我不擅长C ++)。
需要将返回值从uint32_t
更改为uint64_t
:
#include <stdint.h>
uint64_t xor128(void) {
static uint64_t x = 123456789;
static uint64_t y = 362436069;
static uint64_t z = 521288629;
static uint64_t w = 88675123;
uint64_t t;
t = x ^ (x << 11);
x = y; y = z; z = w;
return w = w ^ (w >> 19) ^ t ^ (t >> 8);
}
答案 0 :(得分:5)
将您的所有uint32_t
类型更改为uin64_t
,您将获得相同的结果。区别在于uint32_t
与python整数类型的无限精度之间的精度。