1
votes

I am trying to do some anaylsis and for 'reasons' I want objects in my programm to each have their own seeds but no global seeds. Can I accomplish something like this ?

a = random.seed(seed1) 
b = random.seed(seed1)

for a in range(5) :
    print a.random(), b.random()

The expect output would be

0.23 0.23 
0.45 0.45 
0.56 0.56 
0.34 0.34 

etc... Obviously a super contrived example -- These separate seed will be buried in objects and correspond to specific things. But first step is getting something like this to work.

How can I have python maintain multiple seeded randoms ?

3
I don't see why not, its not like you're sharing the memory between the two variables, have you tried coding it yet? - reticentroot
random doesnt have an init to return an object that I can see, which I used in my code because I wish it did. each time I call seed it is affecting a global seed based of my testing. I tired coding it and get a Nonetype has no random error since random.seed() doesnt actually retrun anything. this is python 2.7 btw - gbtimmon

3 Answers

8
votes

You need to use a random.Random class object.

from random import Random

a = Random()
b = Random()

a.seed(0)
b.seed(0)

for _ in range(5):
    print(a.randrange(10), b.randrange(10))

# Output:
# 6 6
# 6 6
# 0 0
# 4 4
# 8 8

The documentation states explicitly about your problem:

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

0
votes

Then, this may help you:

>>> for _ in range(5): 
          rn=random.randint(1,100) 
          print(rn, rn) 

Output is:
38 38

98 98

8 8

29 29

67 67

-1
votes

I hope you are just looking for random numbers as mentioned in above output:

Here is some code. Please check, if can be helpful for you:

>>> for i in range(5):
        print(random.randint(1,100), random.randint(1,100))

Output will be as:

14 93

51 62

20 12

9 3

52 71