First time here? Check out the FAQ!

Ask Your Question
2

Fast (uniform) random integer generation

asked 10 years ago

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.

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
2

answered 10 years ago

tmonteil gravatar image

updated 10 years ago

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
Preview: (hide)
link

Comments

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

Anschel Schaffer-Cohen gravatar imageAnschel Schaffer-Cohen ( 10 years ago )

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 ( 10 years ago )
2

answered 10 years ago

vdelecroix gravatar image

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

Preview: (hide)
link

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 ( 10 years ago )

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: 10 years ago

Seen: 7,313 times

Last updated: Jul 12 '14