We know the ‘sample’ function creates a random sample of elements from a vector. But if you want to get a random sample between two limits, ‘runif’ is the function. Here is a plot of 1000 samples between 0 and 1.
runif(1000, min = 0, max = 1)
Now, here is a question. If A and B are two random points between 0 & 1, what is the probability A / B lies between 1 and 2?
itr <- 1000000
toss <- replicate(itr, {
sa_A <- runif(1)
sa_B <- runif(1)
sam <- sa_A / sa_B
if(sam >= 1 & sam <= 2) {
counter <- 1
}else{
counter <- 0
}
})
mean(toss)
0.25
Here is a graphical representation. X/Y between 1 and 2 implies the area between two lines X / Y = 1 (Y = X) and X/Y = 2 (Y = X/2).
The area between the two lines = 1 x 1 – (1/2) x 1 x 1 – (1/2) x 1 x (1/2) = 1 – 0.5 – 0.25 = 0.25.