【问题标题】:XorShift number generationXorShift 数字生成
【发布时间】:2014-03-20 21:00:57
【问题描述】:

用 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 编写的相同代码(可以在 Wikipedia 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);
}

【问题讨论】:

  • uint32_t 的最大值有多大?给你。
  • 如果您能帮我用 Python 编写正确的 xor_shift 函数,我将不胜感激,因为我的显然行不通:(
  • 十进制无符号32位整数的最大值:4294967295 (UINT32_MAX),小于Python中的结果,Python会按需自动提升整数类型。
  • 好的,但是在将其更改为 uint64_t 后,我​​的结果仍然与 Python 中的结果不同。 W1=3869459946 W2=2371244454 W3=4211465258

标签: python c++ c xor shift


【解决方案1】:

将所有uint32_t 类型更改为uin64_t,您将获得相同的结果。区别在于uint32_t的精度和python整数类型的无限精度。

【讨论】:

  • 将 uint32_t 更改为 uint64_t 后,我​​得到:W1=3869459946 W2=2371244454 W3=4211465258 与 Python 值还有什么不同...
  • @PiterD 是否也更改了返回值类型和t 的类型?在进行这些更改的系统上,我得到与 python 程序完全相同的值。
  • 哦,是的,你说得对,我没有更改返回值。现在结果是一样的 :) 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多