[Tutor] seed & random !? [calling random.seed() more than once]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 14 Oct 2001 17:17:59 -0700 (PDT)

```On Sun, 14 Oct 2001, necati kaya wrote:

> I tried to use seed function, but it gave me all the same results. Do

We really don't get truly random numbers out of the 'random' module: what
we get are "pseudorandom" numbers: that is, these numbers look random
enough to be useful.

These pseudorandom numbers are completely determined by a math formula
that starts off with a seed value.  We can almost think of it as shaking a
hat filled with slips of paper, where the seed tells Python exactly how to
shake the hat.  Given a seed number, the random number generator will give
a pseudorandom-looking sequence.

But here's where the analogy to hat shaking in the real world breaks: if
we start off the generator with the same seed, we get back the same random
sequence!  Take a look:

###
>>> random.seed(42)
>>> random.random(), random.random(), random.random()
(0.25420336316883324, 0.46884405296716114, 0.19540525690312815)
>>> random.seed(42)
>>> random.random(), random.random(), random.random()
(0.25420336316883324, 0.46884405296716114, 0.19540525690312815)
###

So it's not quite random: everything depends on the initial seed value.

This pseudorandomness can actually be a good thing: scientists often use
pseudorandom numbers in modeling a natural system.  They do need "random"
looking numbers, but they also need to be able to reproduce their results,
to show other scientists what they've done.  By using a pseudorandom
generator, scientists can get "randomness" and eat their cake too.

Let's go back to your observation:

> I tried to use seed function, but it gave me all the same results. Do

If we call seed() without an initial seeding value, Python will seed our
random number generator with the system clock.  However, the system clock
only has millisecond precision, so if we call seed() too quickly...

###
>>> for i in range(5):
...     random.seed()
...     print random.random(), random.random(), random.random()
...
0.568006638742 0.223572689753 0.61370495775
0.573655982955 0.189610550271 0.806179106218
0.573655982955 0.189610550271 0.806179106218
0.573655982955 0.189610550271 0.806179106218
0.573655982955 0.189610550271 0.806179106218
###

Notice that the first set of numbers is different from the last five:
that's evidence that the system clock "ticked" once at that moment.
Still, the above shows that calling seed() too quickly will break the
"randomness" of our random number generator.

The solution to this mess?  Don't call seed().  *grin*

But seriously, Python does this for you already when it starts up, and in
truth, seed() should only be called, at most, once in a program.