我正在尝试进行一些分析,并且出于“原因”我希望我的程序中的对象每个都有自己的种子,但没有全局种子。我能完成这样的事吗?
a = random.seed(seed1)
b = random.seed(seed2)
for a in range(5) :
print a.random() b.random()
期望输出将是
0.23 0.23
0.45 0.45
0.56 0.56
0.34 0.34
...等 显然是一个超人为的例子 - 这些独立的种子将被埋在物体中并与特定的东西相对应。但第一步是让这样的事情发挥作用。
如何让python维护多个种子randoms?
答案 0 :(得分:2)
您需要使用random.Random
类对象。
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
documentation明确说明了您的问题:
该模块提供的函数实际上是a的绑定方法 隐藏
random.Random
类的实例。你可以实例化你的 拥有Random
的实例来获取不共享状态的生成器。
答案 1 :(得分:0)
然后,这可能会对您有所帮助:
#this program calculates sales commissions and sums the total of all sales commissions the user has entered
print("Welcome to the program sales commission loop")
keep_going='y'
total=0
while keep_going=='y':
#get a salespersons sales and commission rate
sales=float(input( 'Enter the amount of sales ' ))
comm_rate=float(input( 'Enter commission rate ' ))
#calculate the commission
comission= sales * comm_rate
print( "commission is {}".format(comission) )
keep_going=input('Enter y for yes: ')
total += comission
print( "Total is {}".format(total) )
print("You have exited the program. Thet total is",total)
输出是:
38 38
98 98
8 8
29 29
67 67
答案 2 :(得分:-1)
我希望你只是寻找上面输出中提到的随机数:
这是一些代码。请检查,如果对您有所帮助:
None
输出将为:
14 93
51 62
20 12
9 3
52 71