Iterative Binomial Update Without Loop
Can this be done without a loop? import numpy as np n = 10 x = np.random.random(n+1) a, b = 0.45, 0.55 for i in range(n): x = a*x[:-1] + b*x[1:] I came across this setup in a
Solution 1:
You are calculating:
sum( a ** (n - i) * b ** i * x[i] * choose(n, i) for 0 <= i <= n)
[That's meant to be pseudocode, not Python.] I'm not sure of the best way to convert that into Numpy.
choose(n, i)
is n!/ (i! (n-i)!)
, not the numpy choose function.
Using @mathfux
's comment, one can do
import numpy as np
from scipy.stats import binom
binomial = binom(p=p, n=n)
pmf = binomial(np.arange(n+1))
res = np.sum(x * pmf)
So
res = x.copy()
for i inrange(n):
res = p*res[1:] + (p-1)*res[:-1]
is just the expected value of a binomial distributed random variable x.
Post a Comment for "Iterative Binomial Update Without Loop"