简体   繁体   English

Cython随机滚动不会产生预期的输出

[英]Cython random roll does not produce the expected output

I am following this tutorial by Hans Petter Langtangen, in order to understand Cython better for the purpose of fast generation of random numbers. 我正在遵循Hans Petter Langtangen的本教程 ,以便更快地了解Cython,以便快速生成随机数。

The author has the following line: 作者有以下行:

r = 1 + int(rand()/(RAND_MAX*6.0))

in his tutorial, which claims to produce a random integer between 1 and 6. To me, it looks like a mistake, as rand() (cimported from libc.stdlib ) is generating a random integer from 0 to RAND_MAX , so I guess the line 在他的教程中,声称产生1到6之间的随机整数。对我来说,它看起来像是一个错误,因为rand() (从libc.stdlib )生成一个从0到RAND_MAX的随机整数,所以我猜线

r = 1 + int(6*rand()/(RAND_MAX(1.0))

should be more appropriate there. 应该更适合那里。 So I have created a little Cython script that should roll a random integer between 1 and n , printing debug messages while doing so. 所以我创建了一个小的Cython脚本,它应该在1和n之间滚动一个随机整数,同时打印调试消息。 Here's the script: 这是脚本:

    from libc.stdlib cimport rand, RAND_MAX

    def print_rand(int n):
        cdef int r
        print "max", RAND_MAX
        cdef int roll
        roll = rand()
        print "roll", roll
        r = 1 + int(n*roll/(RAND_MAX*1.0))
        print r

Then I have compiled the script using the following setup.py script: 然后我使用以下setup.py脚本编译了脚本:

    from distutils.core import setup
    from distutils.extension import Extension
    from Cython.Distutils import build_ext

    setup(name='Random print',
          ext_modules=[Extension('_rand', ['rand.pyx'],)],
          cmdclass={'build_ext': build_ext},)

running it via 通过运行它

python setup.py build_ext --inplace

For testing, I opened IPython , and the following mystery occurred: 为了测试,我打开了IPython ,发生了以下谜团:

In [1]: import _rand

In [2]: _rand.print_rand(1000)
max 2147483647
roll 1804289383
1

but that doesn't make sense, as 但这没有意义,因为

In [3]: 1 + int(1000*1804289383/(2147483647*1.0))
Out[3]: 841

What am I missing here? 我在这里错过了什么?

The multiplication 乘法

n*roll

has a result too large to fit into a Cython int. 结果太大,无法融入Cython int。 Unlike with Python ints, which automatically switch to arbitrary-precision representation when such a thing happens, Cython handles overflow like C. That generally means the high bits that don't fit are discarded; 与Python ints不同,它会在发生这种情况时自动切换到任意精度表示,Cython会像C一样处理溢出。这通常意味着丢弃不适合的高位; I am not sure whether it is undefined behavior in Cython (in which case much worse things can happen), or whether Cython guarantees specific overflow handling. 我不确定它是否是Cython中的未定义行为(在这种情况下会发生更糟糕的事情),或者Cython是否保证特定的溢出处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM