R - 计算变量中 6 的数量
R - Count the Number of 6s in a Variable
我正在尝试编写一种算法,使我能够计算在可变数量的骰子上掷出 6 的概率。这是我拥有的:
num.dice <- 6
## x is the number of iterations
x <- 1
a <- c()
while(x < 1000) {
a[(x:x)] <- sum(sample(1:6, num.dice, replace=TRUE)==1)
x <- x + 1
}
sum(a)/1000
我更愿意使用 monte carlo 风格的模拟,但我相信我无法正确计算 6s。
我哪里错了?
我的数学有点生疏,但这就是你要找的东西吗?
library( gtools )
num_dice <- 1:6
lapply(num_dice, function(x) {
sum(
apply(
permutations( 6, x, 1:6, repeats.allowed = TRUE ),
1,
function(y) any( y == 6 )
)
) / 6^x
})
[[1]]
[1] 0.1666667
[[2]]
[1] 0.3055556
[[3]]
[1] 0.4212963
[[4]]
[1] 0.5177469
[[5]]
[1] 0.5981224
[[6]]
[1] 0.665102
我正在尝试编写一种算法,使我能够计算在可变数量的骰子上掷出 6 的概率。这是我拥有的:
num.dice <- 6
## x is the number of iterations
x <- 1
a <- c()
while(x < 1000) {
a[(x:x)] <- sum(sample(1:6, num.dice, replace=TRUE)==1)
x <- x + 1
}
sum(a)/1000
我更愿意使用 monte carlo 风格的模拟,但我相信我无法正确计算 6s。
我哪里错了?
我的数学有点生疏,但这就是你要找的东西吗?
library( gtools )
num_dice <- 1:6
lapply(num_dice, function(x) {
sum(
apply(
permutations( 6, x, 1:6, repeats.allowed = TRUE ),
1,
function(y) any( y == 6 )
)
) / 6^x
})
[[1]]
[1] 0.1666667
[[2]]
[1] 0.3055556
[[3]]
[1] 0.4212963
[[4]]
[1] 0.5177469
[[5]]
[1] 0.5981224
[[6]]
[1] 0.665102