概率函数生成值而不是随机调用
Probability function to generate values instead of calling random
在我的 python 代码中,有几个地方我的人口中每个人都有 x
发生某些事情的可能性,但我只需要受影响的人数。
amount = 0
population = 500
chance = 0.05
for p in range(population):
if random.random() < chance:
amount += 1
我的直觉告诉我,必须有比调用 random.random() 500 次更简单的方法来执行此操作。一些我不知道的数学或统计术语或函数。
amount = population * chance * random.random()
对于我的需要来说变化太大了。
n个0-1个随机变量之和的分布,每个随机变量的概率为p称为一个binomial distribution with parameters n and p. I believe numpy.random.binomial
会为所欲为。
诀窍不是执行离散循环,而是使用随机模型(二项分布)来简化它。
对于特殊值范围,您可以将一个分布转换为另一个分布。对于大量实验(在您的情况下 n=500
),二项分布 can be approximated to a normal distribution.
可能如果你不想安装numpy
你可以近似这个。
对于您的情况(n = 500
、p = 0.05
):
这样你就可以再次使用 random
模块了:
random.normalvariate(25, 4.87340)
我会推荐 numpy
的解决方案。它应该是准确和最快的解决方案。
在我的 python 代码中,有几个地方我的人口中每个人都有 x
发生某些事情的可能性,但我只需要受影响的人数。
amount = 0
population = 500
chance = 0.05
for p in range(population):
if random.random() < chance:
amount += 1
我的直觉告诉我,必须有比调用 random.random() 500 次更简单的方法来执行此操作。一些我不知道的数学或统计术语或函数。
amount = population * chance * random.random()
对于我的需要来说变化太大了。
n个0-1个随机变量之和的分布,每个随机变量的概率为p称为一个binomial distribution with parameters n and p. I believe numpy.random.binomial
会为所欲为。
诀窍不是执行离散循环,而是使用随机模型(二项分布)来简化它。
对于特殊值范围,您可以将一个分布转换为另一个分布。对于大量实验(在您的情况下 n=500
),二项分布 can be approximated to a normal distribution.
可能如果你不想安装numpy
你可以近似这个。
对于您的情况(n = 500
、p = 0.05
):
这样你就可以再次使用 random
模块了:
random.normalvariate(25, 4.87340)
我会推荐 numpy
的解决方案。它应该是准确和最快的解决方案。