Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 views
in Technique[技术] by (71.8m points)

python maintain two different random instance

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...