我想确认一下
a = [random.choices([0,1],weights=[0.2,0.8],k=1) for i in range(0,10)] 在概率上做的事情与
a = random.choices([0,1],weights=[0.2,0.8],k=10) 特别是,我希望两者都能从集合{0, 1 }中进行10次独立抽奖,概率分别为0和0.8,对吗?
谢谢!
发布于 2019-10-17 09:41:01
documentation似乎表明,在运行以下实验后,两者在概率上是相同的:
from collections import defaultdict
import pprint
import random
results1 = defaultdict(int)
results2 = defaultdict(int)
for _ in range(10000):
a = [random.choices([0,1],weights=[0.2,0.8],k=1) for i in range(0,10)]
for sublist in a:
for n in sublist:
results1[n] += 1
for _ in range(10000):
a = random.choices([0,1],weights=[0.2,0.8],k=10)
for n in a:
results2[n] += 1
print('first way 0s: {}'.format(results1[0]))
print('second way 0s: {}'.format(results2[0]))
print('first way 1s: {}'.format(results1[1]))
print('second way 1s: {}'.format(results2[1]))我在两种方法之间看到了非常相似的结果。
发布于 2019-10-17 09:45:43
正如其他人所提到的,documentation在这方面是明确的,您可以通过在每次调用之前设置种子来进一步验证,例如:
import random
random.seed(42)
print([random.choices([0, 1], weights=[0.2, 0.8], k=1)[0] for i in range(0, 10)])
random.seed(42)
print(random.choices([0, 1], weights=[0.2, 0.8], k=10))输出
[1, 0, 1, 1, 1, 1, 1, 0, 1, 0]
[1, 0, 1, 1, 1, 1, 1, 0, 1, 0]此外,只设置一次,确实会导致不同的结果,正如人们可能预期的那样:
random.seed(42)
print([random.choices([0, 1], weights=[0.2, 0.8], k=1)[0] for i in range(0, 10)])
print(random.choices([0, 1], weights=[0.2, 0.8], k=10))输出
[1, 0, 1, 1, 1, 1, 1, 0, 1, 0]
[1, 1, 0, 0, 1, 1, 1, 1, 1, 0]https://stackoverflow.com/questions/58423650
复制相似问题