Thursday, February 5, 2015

R8. Rolling Two Dice in R

There are 5000 trials of rolling 2 dice. The sum of the 2 dices go from 2 to 12.


x1 and x2 are random samples of {1,2,3,4,5,6}, uniformly distributed. They are both vectors of length 5000.


We have to use the double brackets in the plots to return a vector from the data frame.

# ex8.R
num_samples <- 5000
x1 <- sample(6, num_samples, replace = T)
x2 <- sample(6, num_samples, replace = T)
df <- data.frame(x1,x2)
df['sum'] <- df['x1'] + df['x2']
x <- numeric(13-2)
for (i in 2:12) {
  x[i-1] <- sum(df['sum']==i)
}
df1 <- data.frame(x, row.names = 2:12)
df1['cum_x'] <- cumsum(df1['x'])
df1['cum_p'] <- df1['cum_x']/num_samples
x_lim <- c(1:6,5:1)
x_lim <- num_samples/36 * x_lim
df1['x_lim'] <- x_lim
df1['cum_lim'] <- cumsum(df1['x_lim'])
df1['cum_p_lim'] <- df1['cum_lim']/num_samples
print(df1)
err_df <- df1['cum_p_lim']-df1['cum_p']
err <- sd(err_df[,1])
print(sprintf('error = %.8f',err))
plot(2:12, df1[['cum_p']], type = 'l', col = 'red', 
     ylab = 'Cum Prob', xlab = 'x')
lines(2:12, df1[['cum_p_lim']], col = 'blue')
#     x cum_x  cum_p    x_lim   cum_lim  cum_p_lim
# 2  130   130 0.0260 138.8889  138.8889 0.02777778
# 3  305   435 0.0870 277.7778  416.6667 0.08333333
# 4  408   843 0.1686 416.6667  833.3333 0.16666667
# 5  584  1427 0.2854 555.5556 1388.8889 0.27777778
# 6  666  2093 0.4186 694.4444 2083.3333 0.41666667
# 7  851  2944 0.5888 833.3333 2916.6667 0.58333333
# 8  701  3645 0.7290 694.4444 3611.1111 0.72222222
# 9  553  4198 0.8396 555.5556 4166.6667 0.83333333
# 10 377  4575 0.9150 416.6667 4583.3333 0.91666667
# 11 301  4876 0.9752 277.7778 4861.1111 0.97222222
# 12 124  5000 1.0000 138.8889 5000.0000 1.00000000
# [1] "error = 0.00329718"

Output:

No comments:

Post a Comment