Random randomness

Tim Peters tim.one at home.com
Wed Jan 23 18:02:41 EST 2002


[W. Jarrett Campbell]
> I'm working on a project that requires a random number generated with the
> same value each time the program is run but I'm seeing some behavior I
> cannot explain.  Could someone explain to me why the following
> code does not result in two random numbers where a = b?
>
> FYI, I'm running Python 2.1 on win32s...
>
> C:\>python
> ActivePython 2.1, build 210 ActiveState)
> based on Python 2.1 (#15, Apr 19 2001, 10:28:27) [MSC 32 bit (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import random
> >>>
> >>> random.seed(10)
> >>> a=random.gauss(0,1)
> >>> random.seed(10)
> >>> b=random.gauss(0,1)
> >>> print a
> 1.14050714147
> >>> print b
> 0.566965824829

Look at the source for random.py.  The gauss() method uses the usual (for
Gaussian distributions) trick of generating two deviates per call, returning
one and saving the other internally to return on the next call.  That hidden
state isn't affected by seed().  Do *pairs* of calls to gauss() and you'll
feel better <wink>:

>>> import random
>>> random.seed(10)
>>> random.gauss(0, 1)
1.1405071414724208
>>> random.gauss(0, 1)
0.5669658248288183        # note this is what your "print b" did
>>> random.seed(10)
>>> random.gauss(0, 1)    # same as 1st call before
1.1405071414724208
>>> random.gauss(0, 1)    # same as 2nd call before
0.5669658248288183
>>>

If your Python is recent enough, random's getstate() and setstate() methods
can be used to save/restore the entire state (including gauss's hidden
state).

>>> random.seed(10)
>>> s = random.getstate()
>>> random.gauss(0, 1)
1.1405071414724208
>>> random.setstate(s)
>>> random.gauss(0, 1)
1.1405071414724208
>>>

But none of this should be an issue if the granularity you're after is "each
time the program is run".





More information about the Python-list mailing list