R中的Coin Toss游戏

时间:2013-09-27 08:29:19

标签: r statistics probability

所以试图模拟一个硬币折腾游戏,如果你有头脑,你可以加倍你的钱,如果你有故事,你可以减半。如果你从x money开始,想要看看你在投掷后得到的东西

然而,我不知道如何以一种干净的方式解决这个问题,而不仅仅是做一个forloop to n。

有没有一些干净的方法来做到这一点?

4 个答案:

答案 0 :(得分:7)

您可以使用sample创建times 0.5times 2的列表。

sample_products = sample(c(0.5, 2), 100, replace = TRUE)
> sample_products
  [1] 0.5 2.0 0.5 2.0 2.0 0.5 2.0 0.5 2.0 2.0 0.5 0.5 0.5 0.5 2.0 2.0 0.5 0.5
 [19] 2.0 2.0 0.5 0.5 0.5 2.0 2.0 2.0 2.0 0.5 0.5 2.0 2.0 2.0 2.0 2.0 2.0 0.5
 [37] 2.0 2.0 2.0 0.5 2.0 2.0 0.5 0.5 0.5 2.0 0.5 2.0 2.0 0.5 2.0 2.0 2.0 2.0
 [55] 0.5 2.0 0.5 2.0 0.5 0.5 0.5 2.0 2.0 2.0 2.0 0.5 2.0 0.5 0.5 2.0 0.5 0.5
 [73] 0.5 2.0 0.5 0.5 0.5 2.0 2.0 0.5 2.0 0.5 0.5 0.5 2.0 2.0 2.0 2.0 0.5 0.5
 [91] 2.0 0.5 0.5 0.5 0.5 0.5 0.5 0.5 2.0 0.5

并获得这些产品的累积效果:

cumulative_prod = prod(sample_products)

并包括起始资金:

 start_money = 1000
 new_money = cumulative_prod * start_money

请注意,对于较大的采样尺寸,cumulative_prod会向1收敛,为一个公平的硬币(sample是)。

答案 1 :(得分:3)

如果要运行多次迭代,可以循环使用

n = 10

toss <- round(runif(n),0)
toss[toss == 0] = -1
toss <- 2^toss

Reduce(x = toss,'*')

答案 2 :(得分:3)

这不是最好的方法(我确信有很多更好的方法),不过,你可以把它视为了解如何去做的一个非常好的起点

> set.seed(1)
> x <- 100   # amount of money
> N <- 10    #number of throws
> TH <- sample(c("H", "T"), N, TRUE)  # Heads or Tails, drawin "H" or "T" with same probability
> sum(ifelse(TH=="H", 2*x, 0.5*x)) # final amount of money
[1] 1100

此外,您可以编写一个函数,将初始金额x和试验次数N

作为参数。
> head.or.tails <- function(x, N){
   TH <- sample(c("H", "T"), N, TRUE)  # Heads or Tails
   sum(ifelse(TH=="H", 2*x, 0.5*x)) # final amount of money  
 }
> 
> set.seed(1)
> head.or.tails(100, 10)
[1] 1100

为了避免ifelse部分,您可以写sample(c(0.5, 2), 100, replace = TRUE)而不是sample(c("H", "T"), N, TRUE),请参阅@Paul Hiemstra回答。

答案 3 :(得分:1)

如果你开始了解这类事情,我很想在日志空间工作,即为胜利添加一个并减去一个。你可以像其他人一样sample,即@Paul的回答。

y <- sample(c(-1,1), 100, replace=TRUE)
plot(cumsum(y), type="s")

如果您想转换回“奖金”,您可以这样做:

plot(2^cumsum(y)*start_money, type="s", log="y", xlab="Round", ylab="Winnings")

这看起来非常相似,但y轴将在奖金中。

如果你对像这样的随机过程不熟悉,看到很多“获胜”或“失败”的条纹会很有趣。如果你想知道它们有多长,rle函数在这里很有用,例如:

table(rle(y)$len)

将打印这些运行长度的频率,这可能会出乎意料地长。您可以使用负二项分布来查看它的来源:

plot(table(rle(y)$len) / length(y))
points(1:15, dnbinom(1:15, 1, 0.5), col=2)

虽然你可能需要使用更大的样本(即1000个或更多样本)才能看到相同的“形状”。

相关问题