Description Usage Arguments Value Examples
This is code that performs rejection sampling on a continuous random variable
1 | rejection_samplr(n, pdf, a, b, C)
|
n |
the number of samples |
pdf |
a function that is the pdf of the random variable that you wish to sample from |
a |
a numeric that is the lower bound of the random variable you wish to sample from |
b |
a numeric that is the upper bound of the random variable you wish to sample from, so P(a ≤ X ≤ b) = 1 |
C |
a numeric that is such that f(x) ≤ C for all values of x |
a random sample of size n from the rv with pdf provided
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | ## sampling from custom pdf
my_pdf <- function(x) {
ifelse(x>=0 & x<=2, (x/2), 0)}
sim_data <- rejection_samplr(30000, my_pdf, 0,2,1)
hist(sim_data, probability = TRUE)
curve(my_pdf(x), col = "red", add = TRUE)
## sampling from dunif
sim_data <- rejection_samplr(1300, dunif, 0,1,2)
hist(sim_data, probability = TRUE)
curve(dunif(x,0,1), col = "red", add = TRUE)
## sampling from beta
sim_data <- rejection_samplr(1300, pdf_beta, a = 0,b = 1,C =1.5)
pdf_beta <- function(x) {
dbeta(x, 2, 3)
}
hist(sim_data, probability = TRUE)
curve(dbeta(x,2,3), col = "red", add = TRUE)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.