Agostino Agostino - 1 year ago 132
Python Question

Generate random integer without an upper bound

I want to generate a random seed in a predictable way.

I was hoping to do this

seed = 12345
prng_0 = random.Random(seed)
prng_1 = random.Random(prng_0.rand_int(0))

is the lower bound, but it turns out I need to give it an upper bound as well. I don't want to set a fixed upper bound.

If you are curious about my reason, I'm doing this because I need reproducibility when testing. Namely, this is a function receiving a seed and building its prng,
, then calling multiple times another function that needs to receive a different seed every time.

def funct_a(seed=None):
prng_1 = random.Random(seed)
prng_2 = numpy.random.RandomState(prng_1.randint(0, 4294967296))

def funct_b(seed=None):
prng_0 = random.Random(seed)
for i in range(0, 5):
seed = prng_0.randint(0) # not working, needs upper bound

funct_b(12345) # test call

EDIT: interestingly enough, numpy (which I'm also using) has a definite upper seed value, as testified by the doc and by this error

ValueError: Seed must be between 0 and 4294967295

Answer Source

When I don't want an upper bound I'll often use sys.maxint for the upper bound as an approximation

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download