# Using R to calculate probability of rolling 2 numbers in 20 throws [closed]

We have an 8-sided die. Throwing it 20 times, what is the probability of rolling a number larger than 6 at least 12 times and at most 16 times?

If you know of an efficient program to write so that I won't have to type in the maths manually, I would be so happy.

The answer by CoolSerdash shows you how to simulate the probability of interest. Here is a direct probability calculation without simulation:

sides   <- 8    # Number of sides of the die
throws  <- 20   # Number of throws
no_cut  <- 6    # Cut-off value (must roll above this)
n_lower <- 12   # Lower bound
n_upper <- 16   # Upper bound

prob <- (sides - no_cut)/sides;
pbinom(n_upper, throws, prob) - pbinom(n_lower-1, throws, prob);

[1] 0.000935362


Here is a quick implementation. I'm sure there are more efficient ways.

d <- 8        # Sides of the die
throws <- 20  # Number of throws
no_cut <- 6   # Number at least on die
n_lower <- 12 # Lower cutoff
n_upper <- 16 # Upper cutoff

n_sim <- 1000000 # Number of simulations

res <- NULL

res <- replicate(n_sim, {
x <- sample.int(d, size = throws, replace = TRUE)
s <- sum(x > no_cut)
(s >= n_lower && s <= n_upper)
})

sum(res)/n_sim # simulated probability