# Fast (uniform) random integer generation

I'm doing some largish experiments involving randomness, and I think random number generation may be the bottleneck. Is there a way to make the random number generator significantly faster without sacrificing the validity of results? I don't especially care that the RNG be cryptographically secure or anything like that.

edit retag close merge delete

Sort by » oldest newest most voted

Sage includes numpy, you can compare the different timings:

sage: %timeit [random.randint(0,10) for i in xrange(1000)]
100 loops, best of 3: 5.61 ms per loop
sage: %timeit [random.randrange(0,11) for i in xrange(1000)]
100 loops, best of 3: 4.82 ms per loop

sage: import numpy
sage: %timeit [numpy.random.random_integers(0,10) for i in xrange(1000)]
1000 loops, best of 3: 1.5 ms per loop
sage: %timeit numpy.random.random_integers(0,10,1000)
10000 loops, best of 3: 53.7 µs per loop

more

Hi, I got a question unrelated to this one but to your code. If I stupidly copy and paste it in a sagenb.org notebook, it throws different errors like 'invalid syntax'. The version that works for me is timeit('[randint(0,10) for i in xrange(1000)]') timeit('[randrange(0,11) for i in xrange(1000)]') import numpy timeit('[numpy.random.random_integers(0,10) for i in xrange(1000)]') timeit('numpy.random.random_integers(0,10,1000)') Can someone explain this to me or give me a hint for which keywords I have to search? Thanks in advance.

Hello,

Just to complete Thierry, answer I guess the most sageish way would be

sage: ZZ.random_element(0,10)
3


It is as fast as numpy and has the advantage of supporting arbitrary precision number. If you want something really fast see how ZZ.random_element is implemented using cython and gmp integers.

Vincent

more

It doesn't actually seem to be as fast as numpy, which runs in about a 40th of the time in my benchmark.