I would like to use a Poisson test function, whereby an event occurs or not according to a given probability p. Python's random module does not seem to have something like this, thus I figured out
- Turn probability p into a fraction
- randomly pick an integer.
- Success is smaller - or - equal to the numerator from a range of integers equal to the denominator.
I, however believe that this is not the most efficient piece of code for the given task. I also doubt about its correctness, nonetheless I think it shoud be if random.randrange(int) works according to uniform distribution.
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
Any suggestions???
Thanks!
Aucun commentaire:
Enregistrer un commentaire