Random Cython movie does not produce expected result

I am following this tutorial by Hans Petter Langtangen to better understand Cython in order to quickly generate random numbers.

The author has the following line:

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

in his tutorial, which claims to create a random integer from 1 to 6. It seems to me that this is a mistake, because rand()(cimported from libc.stdlib) generates a random integer from 0 to RAND_MAX, so I assume that the line

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

should be more appropriate. Therefore, I created a small Cython script that should roll a random integer from 1 to n, while printing debug messages. 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 compiled the script using the following setup.pyscript:

    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},)

run it through

python setup.py build_ext --inplace

IPython, :

In [1]: import _rand

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

,

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

?

+4
1

n*roll

, Cython int. Python ints, , , Cython , C. , , , ; , undefined Cython ( ), Cython .

+3

Source: https://habr.com/ru/post/1545803/


All Articles