我保证这不是正义另一个掷骰子的家庭作业问题。我实现了一个函数,用于计算滚动s
n
边骰子时获得少于总和m
的概率。我的函数适用于较小值n
,但是对于较大值n
我却发现了奇怪的结果。参见附图。任何人都知道发生了什么事吗?
probability <- function(s, m, n) {
i <- 0:((s-1-n) / m)
m^(-n) * sum((-1)^i * choose(n, i) * choose(s - 1 - i * m, n))
}
n <- 1:90 # number of dice
m <- 6 # number of sides
s <- floor(mean(1:m)*n) # sum of faces
p <- mapply(probability, s = s, m = m, n = n)
plot(n, p, main = paste("probability of rolling less than floor(", mean(1:m),"* n) as sum of n rolls of a", m, "sided dice"))
答案 0 :(得分:1)
正如在origianl问题的评论中提到的那样,问题在于概率函数正在要求R计算非常大的数字(choose(80,40) = 1.075072e+23
),而我们正在达到R的数值精度极限。
不涉及大量数字而是使用大量数字的另一种方法是运行蒙特卡洛模拟。这将生成骰子掷骰总和的分布,并将观察到的总和与该分布进行比较。运行需要更长的时间,但更容易实现,并且不会出现数值精度问题。
mc <- Vectorize(function(s, m, n, reps = 10000) {
x <- replicate(reps, sum(sample(m, n, replace = TRUE)))
ecdf(x)(s-1)
})
n <- 1:90 # number of dice
m <- 6 # number of sides
s <- floor(mean(1:m)*n) # sum of faces
analytic_prob <- mapply(probability, s = s, m = m, n = n)
mc_prob <- mapply(mc, s = s, m = m, n = n)
plot(n, analytic_prob, main = paste("probability of rolling less than floor(", mean(1:m),"* n) as sum of n rolls of a", m, "sided dice"),
sub = "monte carlo in red")
points(n, mc_prob, col = "red")
答案 1 :(得分:0)
问题是由R的数值精度限制引起的。正如评论者所指出的,我上面计算的n个选择k值确实非常大(choose(80,40) = 1.075072e+23
)。
我们可以使用日志来尝试将问题保持在R的计算范围内。这是Ramanujan方法的实现。不幸的是,近似复合物中的误差以及精度下降得更快。概率函数需要添加和减去一个非常大的数字序列才能获得介于0和1之间的最终值,并且不能容忍任何不精确性。
probability <- function(s, m, n) {
# Probability of getting less than s
i <- 0:((s-1-n) / m)
c1 <- choose(n, i)
c2 <- choose(s - 1 - i * m, n)
seq <- (-1)^i * (c1 * c2)
m^(-n) * sum(seq)
}
# using the 'ramanujan' method
ramanujan <- function(n){
n * log(n) - n + log(n * (1 + 4*n * (1 + 2*n))) / 6 + log(pi) / 2
}
# confirm Ramanujan works correctly
n <- 1:200
diff <- log(factorial(n)) - ramanujan(n)
plot(n, diff) # r returns inf for factorial(171), but up to there the numbers match
choose
函数。#' This function returns log(choose(n,k))
log_nck <- Vectorize(function(n, k) {
if(n <= k | n < 1 | k < 1) return(log(choose(n,k))) # logs don't like 0 or neg numbers
return((ramanujan(n) - ramanujan(k) - ramanujan(n-k)))
})
# Check that choose function works
n <- seq(10, 100, 10)
k <- seq(5, 50, 5)
c_real <- log(choose(n, k))
c_approx <- log_nck(n, k)
# If we print them, they appear to match
print(c_real)
print(c_approx)
# and the difference shows pretty small errors.
print(c_real - c_approx)
new_probability <- function(s, m, n) {
# Probability of getting less than s
i <- 0:((s-1-n) / m)
c1 <- log_nck(n, i)
c2 <- log_nck(s - 1 - i * m, n)
seq <- (-1)^i * exp(c1 + c2)
return(m^(-n) * sum(seq))
}
n <- 1:90 # number of dice
m <- 6 # number of sides
s <- floor(mean(1:m)*n) # sum of faces
p <- mapply(probability, s = s, m = m, n = n)
newp <- mapply(new_probability, s = s, m = m, n = n)
plot(n, p, main = "Original in black, approximation in red")
points(n, newp, col = "red")