Python如何生成具有位概率的随机数?

2024-10-01 07:47:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要计算出在指定时间内衰变的原子数。我得到了氡-222的半衰期,并由此计算出任何一个原子在1分钟内衰变的概率。在

如果我有x个原子,概率是y,如何计算在1分钟内衰变的原子数?在

我现在有一个非常低效的功能(见下文),但这可能可以更容易地完成。在

def Decay(atomno, decayrate):
    out = 0
    for atom in range(atomno):
        if random.uniform(0,1)<decayrate:
            out += 1
    return out

Tags: in功能fordef时间out概率atom
1条回答
网友
1楼 · 发布于 2024-10-01 07:47:27

听起来你想要一个来自二项分布的随机数,就像numpy.random.binomial产生的。在

对于数量相当大的原子,可以用如下正态分布近似:

from random import normalvariate

def binomialvariate(n, p):
    """
    Generate random number from a binomial distribution
      using a normal-distribution approximation
    """
    return normalvariate(n * p, (n * p * (1 - p)) ** 0.5)

用的像

^{pr2}$

给予

100307.20222237767
99709.2126851899
99834.51936804672
100085.99501737293
100121.93115561221
100379.9532069239
99848.39057702095
99465.46179311829
100357.77320779095
99990.74240156381

相关问题 更多 >