2015-01-06 55 views
0

我想使用泊松測試函數,根據給定的概率發生或不發生事件p。 Python的隨機模塊似乎不具備這樣的事情,所以我想通了Python中的隨機測試模型

  • 的拐彎可能性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

我認爲你需要重新考慮你想要做什麼。泊松分佈描述了在一定的時間間隔內觀察0,1,2,...事件的可能性,因爲該過程具有特定的出現率。你所描述的不是泊松。如果有兩個結果,成功或失敗,並且有一個固定的成功概率,那麼就有一個伯努利隨機變量。 – pjs

回答

0

你的功能是顯然不工作:

>>> 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