I am simulating data using the Rejection method where the density function of X
is given by f(x)= C * e^(x) for all x in [0,1]
. I defined g(x) = 1
and C
to be the maximum of f(x)
which is equal to 1/(e-1)
.
I used the following code to simulate data:
rejection <- function(f, C, g, rg, n) {
naccepts <- 0
result.sample <- rep(NA, n)
while (naccepts < n) {
y <- rg(1)
u <- runif(1)
if ( u <= f(y) / (C*g(y)) ) {
naccepts <- naccepts + 1
result.sample[naccepts] = y
}
}
result.sample
}
f <- function(x) ifelse(x>=0 & x<=1, (exp(x)), 0)
g <- function(x) 1
rg <- runif
C <- 1/(exp(1) -1)
result <- rejection(f, C, g,rg, 1000)
Then, I use the histogram
to compare the simulated data with the curve
of original pdf
as
hist(result,freq = FALSE)
curve(f, 0, 1, add=TRUE)
But the resulted plot is kind of weired! the plot is here so I am looking for any help to clarify what is wrong in my work.