我想迭代100个值并随机选择0或1,但最终得到相等数量的0和1。
下面的代码打印计数:
输出结果为:
下面的代码打印计数:
import random
c_true = 0
c_false = 0
for i in range(100):
a = random.getrandbits(1)
if a == 1:
c_true += 1
else:
c_false += 1
print "true_count:",c_true
print "false_count:",c_false
输出结果为:
true_count: 56
false_count: 44
我希望计数相等
true_count: 50
false_count: 50
我该如何修改代码才能获得所需的结果?
(random.random() >= 1.0*false_count / (true_count+false_count))
就足够了。 - DSM