user196264097
user196264097

Reputation: 887

How does the python random.seed work

I was following this example https://stackoverflow.com/a/9009657/1890488

He has this as outcome

>>> import random
>>> rnd = random.Random(0)
>>> [rnd.randint(0, 10) for i in range(10)]
[9, 8, 4, 2, 5, 4, 8, 3, 5, 6]
>>> rnd = random.Random(0)
>>> [rnd.randint(0, 10) for i in range(10)]
[9, 8, 4, 2, 5, 4, 8, 3, 5, 6]
>>> rnd = random.Random(1)
>>> [rnd.randint(0, 10) for i in range(10)]
[1, 9, 8, 2, 5, 4, 7, 8, 1, 0]

I have few problems

  1. why did first two sequence are same
  2. when we pass 1 as argument dos it mean then how does the first value come as 1

Upvotes: 0

Views: 2720

Answers (2)

user4815162342
user4815162342

Reputation: 155485

The first two sequences are the same because you seeded them with the same value. This is a feature.

Settable seed enables you to intentionally repeat your sequences by reusing the same seed. This can be used, for example, to implement a game replay exactly equivalent to the original, although the game uses a random number generator for in-game encounters or for some AI decisions.

Upvotes: 3

Jarosław Jaryszew
Jarosław Jaryszew

Reputation: 1502

Because it is just a pseudorandom generator. This is a function (in a mathematical sense) that has nice square distribution. Common practice is to use system time in milliseconds as a seed:

rnd = random.Random(int(round(time.time() * 1000)))

Upvotes: 2

Related Questions