R Code for Coin Toss Simulation PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This R code demonstrates a simulation of coin toss experiments, showing how sample size affects the accuracy of probability estimations. The code performs multiple simulations using 100 and 5000 observations, contrasting the different outcomes. It illustrates the concept of fundamental probability and statistical inference.
Full Transcript
> #example_sample.R > #simulations can be used to represent real world experimental results > #for example, given a coin that may not be balanced, what is the p(Head) > #set.seed is used in order to reproduce simulation results > set.seed(13425) > # 100 Bernoulli trials used to simulate the tossing...
> #example_sample.R > #simulations can be used to represent real world experimental results > #for example, given a coin that may not be balanced, what is the p(Head) > #set.seed is used in order to reproduce simulation results > set.seed(13425) > # 100 Bernoulli trials used to simulate the tossing of a coin with P(H) = 0.5 > sample(c(0,1), 100, replace = TRUE) 0 1 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1 1 0 0 0 0 0 0 1 1 0 1 1 0 1 1 0 1 1 0 1 0 0 0 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 1 1 1 0 0 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0 1 0 0 1 1 1 0 0 0 0 0 0 1 1 > > # 100 Bernoulli trials used to simulate the tossing of a coin with P(H) = 0.7 > TossCoin=sample(c(0,1), 100, replace = TRUE,prob=c(0.3,0.7)) > TossCoin 0 0 1 1 1 1 0 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 1 0 0 1 1 1 1 1 0 0 1 1 1 0 1 0 0 1 1 1 1 0 1 0 1 1 1 1 1 1 1 0 1 0 1 1 0 1 1 0 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 1 0 0 0 0 0 1 1 0 1 0 1 1 1 1 1 0 0 1 1 1 1 > sum(TossCoin)/length(TossCoin) 0.68 > > # 5000 Bernoulli trials used to simulate the tossing of a coin with P(H) = 0.7 > TossCoin=sample(c(0,1), 5000, replace = TRUE,prob=c(0.3,0.7)) > sum(TossCoin)/length(TossCoin) 0.7086 > > #fundamental concept: an estimate of P(H) based on 5000 observations > #is "better" than an estimate of P(H) based on 100 observations > > #better = closer to the unknown parameter P(H)=p and with smaller variance > ##----------------------------------------------------# >