0

For part of my code i need to get 'random' numbers that are the same every time that the code is run, and use random.seed(0) to make sure that the same numbers are returned each time. However, at a separate part of the code, i wish to have numbers that vary each time the code is run. Once the seed has been set though, each time any of the random functions are called, the numbers that they return are always the same. How is it possible to combine pre-determined random numbers, with random numbers?

kyrenia
  • 5,431
  • 9
  • 63
  • 93
  • 2
    By using two different PRNG-objects (sometimes called streams). One constant-seeded; one seeded by time or external entropy, depending on the use-case. Hint: ```r = random.Random()```. Remark: this is simpler and more performant compared to get/set internal-states between different uses. – sascha Nov 05 '17 at 12:54
  • 1
    Thanks Sascha - if this was an actual 'answer' i would mark it as the best one for sure! – kyrenia Nov 05 '17 at 13:26

1 Answers1

1

You can use getstate and setstate, something along the lines of

import random

state = random.getstate()  # saving the current state of the generator

random.seed(0)
random.randint(1, 10)

# some more fiddling with random
# ...

random.setstate(state)  # restore the original state

Info from the docs: https://docs.python.org/3.5/library/random.html#random.getstate

DeepSpace
  • 78,697
  • 11
  • 109
  • 154