gpt4 book ai didi

r - R 中 Monty Hall 问题的蒙特卡罗模拟不起作用?

转载 作者:行者123 更新时间:2023-12-02 00:00:12 24 4
gpt4 key购买 nike

我正在 R 中编写一个函数来对 Monty Hall 问题执行蒙特卡罗模拟。当门没有开关时,该函数正在工作 switch == FALSE,但是当我调用 mean(replicate(10000, monty_hall(switch = TRUE))) 时,预期答案约为 0.66,但实际上我得到了 0.25 左右。

这是该函数的代码:

monty_hall = function(switch = logical()){
doors <- c(1,2,3)
names(doors) <- rep(c("goat", "car"), c(2,1))
prize_door <- doors[3]

guess <- sample(doors, 1)
revealed_door <- sample(doors[!doors %in% c(guess, prize_door)],1)
if(switch){
switched_door <- sample(doors[!doors %in% c(guess, revealed_door)],1)
prize_door == switched_door
} else {
prize_door == guess
}
}

我应该进行哪些更改才能获得大约 0.66 的正确输出?

最佳答案

只需将门向量更改为字符即可

monty_hall = function(switch = logical()){
doors <- c("1","2","3")
names(doors) <- rep(c("goat", "car"), c(2,1))
prize_door <- doors[3]

guess <- sample(doors, 1)
revealed_door <- sample(doors[!doors %in% c(guess, prize_door)],1)
if(switch){
switched_door <- sample(doors[!doors %in% c(guess, revealed_door)],1)
prize_door == switched_door
} else {
prize_door == guess
}
}

假设该人选择了 1 号门,奖品在 2 号门,那么剩下要揭晓的是 3 号门。

您将拥有revealed_door <- sample(3,1)这并不像你期望的那样工作,这变成 revealed_door <- sample(c(1,2,3),1)

在函数文档中,只需输入 ?sample

If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x. Note that this convenience feature may lead to undesired behaviour when x is of varying length in calls such as sample(x)

我认为最简单的解决方法是更改​​为字符,但如果您必须使用数值,只需检查向量的长度并返回该值(如果为 1),否则进行示例

关于r - R 中 Monty Hall 问题的蒙特卡罗模拟不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56095777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com