【问题标题】:random testing model in PythonPython中的随机测试模型
【发布时间】:2015-03-04 10:36:19
【问题描述】:

我想使用泊松测试函数,根据给定的概率p,事件发生与否。 Python 的 random 模块似乎没有这样的东西,所以我想通了

  • 把概率p变成分数
  • 随机选择一个整数。
  • 成功小于 - 或 - 等于分母整数范围中的分子。

但是,我认为这不是给定任务最有效的代码。我也怀疑它的正确性,但我认为它应该是 random.randrange(int) 根据均匀分布工作。

def poisson_test(p):

    '''Poisson test with two possible outcomes, where p is success probability'''

    import fractions

    import random

    from decimal import Decimal

    p = Decimal('{0}'.format(p))

    p = fractions.Fraction(p)

    if random.randrange(p.denominator) <= p.numerator :

        return True

    else:

        return False

有什么建议吗???

谢谢!

【问题讨论】:

  • 我认为你需要重新考虑你想要做什么。泊松分布描述了您在固定间隔内观察到 0、1、2、... 的可能性有多大,假设该过程具有指定的发生率。你所描述的不是泊松。如果有两种结果,成功或失败,成功的概率是固定的,你就有一个伯努利随机变量。

标签: python events testing random poisson


【解决方案1】:

您的功能显然不起作用:

>>> from collections import Counter
>>> Counter(poisson_test(0.5) for _ in range(10000))
Counter({True: 10000})

randrange,像香草range排除 stop 参数,例如randrange(2)永远不会成为2,因此函数总是返回True

最小的修复是:

if (random.randrange(p.denominator) + 1) <= p.numerator :

这给出了更明智的结果:

>>> Counter(poisson_test(0.5) for _ in range(10000))
Counter({True: 5024, False: 4976})

或者,使用包含两个参数的randint

if random.randint(1, p.denominator) <= p.numerator :

但更简单的是:

import random

def poisson_test(p):
    """Poisson test with two possible outcomes, where p is success probability."""
    return random.random() <= p

注意程序开头的文档字符串和import 的双引号,每个the style guide

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 2019-07-10
    • 2014-07-25
    • 1970-01-01
    • 2017-12-12
    • 2014-04-22
    • 1970-01-01
    • 2013-05-16
    相关资源
    最近更新 更多