19

I would like to use np.random.seed() in the first part of my program and cancel it in the second part. Again,

  • in the first part of my python file, I want the same random numbers to be generated at each execution
  • in the second part , I want different random numbers to be generated at each execution
u2gilles
  • 6,888
  • 7
  • 51
  • 75

1 Answers1

23

In the first part initialize the seed with a constant, e.g. 0:

numpy.random.seed(0)

In the second part initialize the seed with time:

import time
t = 1000 * time.time() # current time in milliseconds
np.random.seed(int(t) % 2**32)

(the seed must be between 0 and and 2**32 - 1)

Note: you obtain a similar effect by calling np.random.seed() with no arguments, i.e. a new (pseudo)-unpredictable sequence.

Each time you initialize the seed with the same constant, you get the same sequence of numbers:

>>> np.random.seed(0)
>>> [np.random.randint(10) for _ in range(10)]
[5, 0, 3, 3, 7, 9, 3, 5, 2, 4]
>>> [np.random.randint(10) for _ in range(10)]
[7, 6, 8, 8, 1, 6, 7, 7, 8, 1]
>>> np.random.seed(0)
>>> [np.random.randint(10) for _ in range(10)]
[5, 0, 3, 3, 7, 9, 3, 5, 2, 4]

Hence initalizing with the current number of milliseconds gives you some pseudo-random sequence.

fferri
  • 18,285
  • 5
  • 46
  • 95