random.jumpahead: How to jump ahead exactly N steps?
Ben Cartwright
bencvt at gmail.com
Wed Jun 21 18:42:17 EDT 2006
Matthew Wilson wrote:
> The random.jumpahead documentation says this:
>
> Changed in version 2.3: Instead of jumping to a specific state, n steps
> ahead, jumpahead(n) jumps to another state likely to be separated by
> many steps..
This change was necessary because the random module got a new default
generator in 2.3. The new generator uses the Mersenne Twister
algorithm. Pre 2.3, Wichmann-Hill was used. (For more details, search
for "jumpahead" in
http://www.python.org/download/releases/2.3/NEWS.txt)
Unlike WH, there isn't a way to directly compute the Nth number in the
sequence using MT. If you're curious as to why,
textbooks/journals/Google are your friends. :-)
> I really want a way to get to the Nth value in a random series started
> with a particular seed. Is there any way to quickly do what jumpahead
> apparently used to do?
You can always use the old WH generator. It's still available:
>>> import random
>>> wh = random.WichmannHill()
>>> N, SEED = 100, 0
>>> wh.seed(SEED)
>>> for i in range(N): dummy = wh.random()
>>> wh.random()
0.68591619673484816
>>> wh.seed(SEED)
>>> wh.jumpahead(N)
>>> wh.random()
0.68591619673484816
> I devised this function, but I suspect it runs really slowly:
Don't just suspect. Experiment, too. :-)
> def trudgeforward(n):
> '''Advance the random generator's state by n calls.'''
> for _ in xrange(n): random.random()
>
> So any speed tips would be very appreciated.
Python's random generator is implemented in C and is quite fast. In my
tests, your trudgeforward performs acceptably with n<~100000.
"import psyco" usually worth a try when improving execution speed, but
it won't help you here. All the real work is being done in C; the
overhead of the Python interpreter is neglible.
Hope that helps,
--Ben
More information about the Python-list
mailing list