寻找n个骰子的点数和概率,最佳解决方案是什么?
- 求平均值。
- 求标准差。
- 对于小于
x
的数字计算z-score。 - 对于大于
x
的数字计算z-score。 - 将两者都转换为概率。
- 用其中一个概率减去另一个概率。
这是我迄今为止所做的。
# sides - number of sides on one die
def get_mean(sides)
(1..sides).inject(:+) / sides.to_f
end
def 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_mean
end
def get_sigma(variance)
variance ** 0.5
end
# x - the number of points in question
def get_z_score(x, mean, sigma)
(x - mean) / sigma.to_f
end
# Converts z_score to probability
def 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 - sum
end
# 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_2
end
# Run probability for 100 dice
puts probability_of_sum(400, 100)
我关心的是,当我选择x = 200
时,概率为0。这个解决方案正确吗?
平均值= 350
和σ = 17
。这意味着99.7%的值将落在299到401的范围内。(350 +/- 17 * 3) - Pav31