def main pi = [0.1, 0.4, 0.5]
theta = [0.8, 0.6, 0.3]
n = 10 eb = sigma(0..n) do |r| probs = calc_posterior_probability_n(pi, theta, n, r)
max = probs.max
pnr = sigma(0...pi.size) do |i| bernoulli_distribution(n, r, theta[i]) * pi[i] end
ebr = (1 - max) * pnr end puts eb end
def calc_posterior_probability_n(pi, theta, n, r) m = pi.size head_prob = (0...m).map do |i| pi[i] * (theta[i] ** r) * ((1 - theta[i]) ** (n - r)) end.inject(:+)
(0...m).map do |i| (pi[i] * (theta[i] ** r) * ((1 - theta[i]) ** (n - r))) / head_prob end end
def bernoulli_distribution(n, r, theta) combi(n, r) * (theta ** r) * ((1 - theta) ** (n - r)) end
def combi(n, r) fact(n) / (fact(n - r) * fact(r)) end
def fact(n) return 1 if n <= 1 (1..n).inject(:*) end
def sigma(range, &block) range.map do |i| block.call(i) end.inject(:+) end
main
|