-
R 语言模拟投硬币
-
#硬币的正面记为1,反面记为0,开始投掷,只要投出背面就停止。模拟一万次求平均模拟停止时的次数
-
#抛硬币模拟 means=1:10000 out=vector("list",length(means)) for(i in seq_along(means)){ y=NULL repeat{ x=sample(c(0,1),1) y=c(x,y) if(x==0) break } out[[i]]=length(y) } out=unlist(out) str(out) #时间 system.time({ means=1:10000 out=vector("list",length(means)) for(i in seq_along(means)){ y=NULL repeat{ x=sample(c(0,1),1) y=c(x,y) if(x==0) break } out[[i]]=length(y) } out=unlist(out) str(out) })
均匀硬币的正面记为1,反面记为0,开始投掷,只要有一次投掷出“110”这样的结果就停止。
#请问:模拟停止时的次数;模拟一万次,平均投掷次数是?
means=1:10000
out=vector("list",length(means))
for(i in seq_along(out)){
y=paste( as.character( sample(c(0,1),100,replace=T) ),collapse="" )
out[i]=regexpr("110",y)+2}
sum(unlist(out))/10000
system.time({
means=1:10000
out=vector("list",length(means))
for(i in seq_along(out)){
y=paste( as.character( sample(c(0,1),100,replace=T) ),collapse="" )
out[i]=regexpr("110",y)+2}
sum(unlist(out))/10000
})
以上就是模拟的全过程,欢迎感兴趣的小伙伴加我好友博客一起交流!