What is the best solution for finding probability of rolling sum with n dice?I'm solving it by finding
- mean.
- standard deviation.
- z_score for the numbers below
x
- z_score for the numbers above
x
- converting both to probabilities
- subtracting one from the other
This is what I've done so far.
# sides - number of sides on one diedef get_mean(sides) (1..sides).inject(:+) / sides.to_fenddef get_variance(sides) mean_of_squares = ((1..sides).inject {|sum, side| sum + side ** 2}) / sides.to_f square_mean = get_mean(sides) ** 2 mean_of_squares - square_meanenddef get_sigma(variance) variance ** 0.5end# x - the number of points in questiondef get_z_score(x, mean, sigma) (x - mean) / sigma.to_fend# Converts z_score to probabilitydef z_to_probability(z) return 0 if z < -6.5 return 1 if z > 6.5 fact_k = 1 sum = 0 term = 1 k = 0 loop_stop = Math.exp(-23) while term.abs > loop_stop do term = 0.3989422804 * ((-1)**k) * (z**k) / (2*k+1) / (2**k) * (z**(k+1)) / fact_k sum += term k += 1 fact_k *= k end sum += 0.5 1 - sumend# Calculate probability of getting 'х' total points by rolling 'n' dice with 'sides' number of sides.def probability_of_sum(x, n, sides=6) mean = n * get_mean(sides) variance = get_variance(sides) sigma = get_sigma(n * variance) # Rolling below the sum z1 = get_z_score(x, mean, sigma) prob_1 = z_to_probability(z1) # Rolling above the sum z2 = get_z_score(x+1, mean, sigma) prob_2 = z_to_probability(z2) prob_1 - prob_2end# Run probability for 100 diceputs probability_of_sum(400, 100)
What concerns me is, when I pick x = 200
, the probability is 0.Is this correct solution?