Ask Your Question
1

Fast (uniform) random integer generation

asked 2014-07-11 12:34:54 -0500

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
1

answered 2014-07-11 13:29:24 -0500

tmonteil gravatar image

updated 2014-07-11 13:29:39 -0500

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

Comments

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

Anschel Schaffer-Cohen gravatar imageAnschel Schaffer-Cohen ( 2014-07-12 22:56:09 -0500 )edit

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.

god.one gravatar imagegod.one ( 2014-07-13 23:55:07 -0500 )edit
1

answered 2014-07-12 14:45:59 -0500

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

edit flag offensive delete link more

Comments

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-12 22:56:46 -0500 )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

2 followers

Stats

Asked: 2014-07-11 12:34:54 -0500

Seen: 235 times

Last updated: Jul 12 '14