In [11]:
import numpy as np
import matplotlib.pyplot as plt
In [12]:
# Negative binomial is just a sum of geometric variables,
# so we can use convolution method to make things much simpler.
# We apply the direct conversion method to the geometric distribution,
# and sum r geometric variables to get our negative binomial variable.
def neg_binomial(r, p, n=1000):
res = []
for i in range(n):
u = np.random.rand(r)
geo = np.floor(np.log(u) / np.log(1 – p)) + 1
res.append(np.sum(geo))
return np.array(res)
nb = neg_binomial(r=3, p=0.4)
print(np.mean(nb))
10.119