enmasse
enmasse

Reputation: 135

Is it worth changing the seed periodically when using python random number generation?

Assuming I am generating 10,000 random numbers using random.randrange, would changing the seed part way through the generation loop have any meaningful difference on the distribution of values generated compared to using the same seed for all 10,000 random numbers?

import random 

epoch = int(0)

while True:
    if epoch%100 == 0: #every 100 epochs, generate a new seed
        random.seed()  
    random.randrange(1,1000,1)
    epoch += 1

My initial thought is that it wouldn't because even though we know python random is deterministic, each successive run of random.randrange(1,1000,1) would still have equal weighting to be any of the 1000 possible values each epoch. Thoughts?

Upvotes: 1

Views: 753

Answers (2)

Sam Mason
Sam Mason

Reputation: 16213

Calling random.seed without passing any value for a, as you are doing, will likely cause it to fetch state from os.urandom() every time. This might be wasteful as it requests a full 19968 bits, i.e. 624 uint32_ts, every time. Hence, if you are only generating 100 random variates every time you reseed, secrets.randbelow(999)+1 is probably better.

Given that output from the MT19937 can be predicted after just 624 variates then, contrary to what Mark says, this should indeed make it less predictable. Assuming of course that your OS is making a reasonable CSRNG available to os.urandom, recent versions of Linux, OSX, Windows, and most BSDs, are all fine.

Note the MT19937 is especially bad in this regard, especially given the amount of state it has, and there are a number of generators that do much better.

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308520

The output of a pseudo-random number generator is determined by its transition from its current state to the next state. A good generator will have many more bits of state than there are bits in its seed, so periodic reseeding will actually increase the predictability of the sequence. I know there was a practical attack based on this in a system where the seed was unnecessarily restricted to a small number of bits.

Upvotes: 2

Related Questions