模拟抛硬币一周? [英] Simulate coin toss for one week?

查看:62
本文介绍了模拟抛硬币一周?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是家庭作业.我有兴趣在 R 中设置抛硬币的模拟.我想运行一个星期的模拟.R 中是否有一个函数可以让我在一周等时间段内启动和停止模拟?如果一切顺利,我可能想增加模拟时间的长度.

This is not homework. I am interested in setting up a simulation of a coin toss in R. I would like to run the simulation for a week. Is there a function in R that will allow me to start and stop the simulation over a time period such as a week? If all goes well, I may want to increase the length of the simulation period.

例如:

x <- rbinom(10, 1, 1/2)

所以澄清一下,上面代码中的 10 个,我如何让模拟持续一周(一周的试验次数与设定的试验次数)?谢谢.

So to clarify, instead of 10 in the code above, how do I keep the simulation going for a week (number of trials in a week versus set number of trials)? Thanks.

推荐答案

这里的代码将继续运行三秒钟,然后停止并打印总数.

Here is code that will continue to run for three seconds, then stop and print the totals.

x <- Sys.time()
duration <- 3 # number of seconds
heads <- 0
tails <- 0

while(Sys.time() <= x + duration){
  s <- sample(0:1, 1)
  if(s == 1) heads <- heads+1 else tails <- tails+1
  cat(sample(0:1, 1))
}
cat("heads: ", heads)
cat("tails: ", tails)

结果:

001100111000011010000010110111111001011110100110001101101010 ...
heads:  12713
tails:  12836

<小时>

警告说明:

以我机器的速度,我敢打赌你会在本周末之前长时间得到一个浮点错误.换句话说,您可能会达到您的机器允许您存储为整数、双精度、浮点数或您正在使用的任何内容的最大值,然后您的代码将崩溃.

At the speed of my machine, I bet that you get a floating point error long before the end of the week. In other words, you may get to the maximum value your machine allows you to store as an integer, double, float or whatever you are using, and then your code will crash.

因此,您可能需要构建一些错误检查或翻转机制来保护您免受此影响.

So you may have to build in some error checking or rollover mechanism to protect you from this.

要快速说明会发生什么,请尝试以下操作:

For an accelerated illustration of what will happen, try the following:

x <- 1e300
while(is.finite(x)){
  x <- x+x
  cat(x, "\n")
}

R 优雅地处理浮点重载,并返回 Inf.

R deals with the floating point overload gracefully, and returns Inf.

因此,您在模拟中拥有的任何数据现在都丢失了.不可能在任何合理的程度上分析无穷大.

So, whatever data you had in the simulation is now lost. It's not possible to analyse infinity to any sensible degree.

在设计模拟时请记住这一点.

Keep this in mind when you design your simulation.

这篇关于模拟抛硬币一周?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆