Ask Your Question

Fast (uniform) random integer generation

asked 2014-07-11 19:34:54 +0200

Anschel Schaffer-Cohen gravatar image

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 flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted

answered 2014-07-11 20:29:24 +0200

tmonteil gravatar image

updated 2014-07-11 20:29:39 +0200

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
edit flag offensive delete link more


Looks like the last of these is the fastest, thanks.

Anschel Schaffer-Cohen gravatar imageAnschel Schaffer-Cohen ( 2014-07-13 05:56:09 +0200 )edit

Hi, I got a question unrelated to this one but to your code. If I stupidly copy and paste it in a 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. gravatar ( 2014-07-14 06:55:07 +0200 )edit

answered 2014-07-12 21:45:59 +0200

vdelecroix gravatar image


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

sage: ZZ.random_element(0,10)

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.


edit flag offensive delete link more


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

Anschel Schaffer-Cohen gravatar imageAnschel Schaffer-Cohen ( 2014-07-13 05:56:46 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2014-07-11 19:34:54 +0200

Seen: 6,576 times

Last updated: Jul 12 '14