python - Why do I get different results with same random seed, same computer, same program -
i running simulation lot of modules. use random number of times. read input files. use rounding. of course, setting random.seed(1) in first line of program, after importing random.
even though, shouldn't same result running same program same parameters in same computer same input files?
inject source random numbers service modules using it. can replace deterministic version gives predefined sequence of numbers. example prerequisite proper unit testing , applies things time, too.
concerning case, e.g. inject instance of random.random
instead of using global (the 1 provided random
module). generator seeded appropriately (constructor argument) provide reproducible sequences.
bad code:
def simulation(): sum = 0 in range(10): sum += random.random() return sum / 10 # think how test code without # monkey-patching random.random.
good code:
def simulation(rn_provider): sum = 0 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 simple function parameter. classes, use "dependency injection".
btw: remember hearing globals bad? here's example why. ;)
Comments
Post a Comment