I was writing a function (without using the random.poisson function)that generates a random number from a poisson distribution with lambda a.
When running the function with different parameters, I always get 0. I guess it is the algorithm problem but don't know where is wrong.
Here is my code.
#takes a as lambda (mean)
def random_poisson(a):
x = 0
p = 1
while p >= math.exp(a):
i = random.random()
p = p * i
x += 1
return x
Trying out different lambda values:
print(random_poisson(3))
print(random_poisson(5))
print(random_poisson(math.log(5)))
The output:
0
0
0
Thanks so much!
For any positive a
, math.exp(a)
is greater than 1, but p
is 1. The loop condition is never true, the loop is never executed, and your function returns the initial value of x
.