问题
I am running a simulation with a lot of modules. I use random a number of times. I read input files. I use rounding. Of course, I am setting a random.seed(1) in the very first line of my program, immediately after importing random.
Even though, shouldn't I get exactly the same result running the same program same parameters in the same computer with the same input files?
回答1:
Inject the source for random numbers as a service into the modules using it. You can then easily replace it with a deterministic version that gives a predefined sequence of numbers. This is for example a prerequisite for proper unit testing and it also applies to things like the time, too.
Concerning your case, you could e.g. inject an instance of random.Random
instead of using a global (the one provided by the random
module). This generator could then be seeded appropriately (constructor argument) to provide reproducible sequences.
Bad code:
def simulation():
sum = 0
for i in range(10):
sum += random.random()
return sum / 10
# Think about how to test that code without
# monkey-patching random.random.
Good code:
def simulation(rn_provider):
sum = 0
for i in range(10):
sum += rn_provider()
return sum / 10
rng1 = random.Random(0)
sum1 = simulation(rng1.random)
rng2 = random.Random(0)
sum2 = simulation(rng2.random)
print(sum1 == sum2)
The code here uses a simple function parameter. For classes, you could also use "dependency injection".
BTW: Remember hearing that globals are bad? Here's your example why. ;)
来源:https://stackoverflow.com/questions/35231087/why-do-i-get-different-results-with-same-random-seed-same-computer-same-progra