Description Usage Arguments Details Value See Also Examples
View source: R/rejection_sampling.R
The rejection_sampling
function operator creates a function that draws
samples from a given probability density function.
1 | rejection_sampling(f_den, g_den, g, M)
|
f_den |
S3 object of class |
g_den |
S3 object of class |
g |
|
M |
strictly positive numeric scalar; satisfies |
Rejection sampling uses g
to draw samples and accepts/rejects
these samples according to the densities f_gen
and g_den
,
such that the resulting samples are f_den
-distributed. Many rejected
samples result in longer runtimes. To prevent this M
should be
chosen as small as possible, satisfying f_den$fun(x) <=
M*g_den$fun(x)
for all numeric scalar inputs x
.
A function taking a single numeric scalar argument n
,
returning n
f-den
distributed random numbers.
Density
for more information about densities.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | custom_den <- function(x) {
ret <- 1 + sin(2*pi*x)
ret[x < 0 | 1 < x] <- 0
ret
}
f_den <- Density(custom_den, c(0,1))
g_den <- Density(dunif)
custom_sampler <- rejection_sampling(f_den, g_den, runif, 2)
x <- seq(-0.5, 1.5, by=0.01)
y <- f_den$fun(x)
plot(x, y, type="l", main="Custom density: 1 + sin(2*pi*x)", ylab="density")
n <- 65
points(custom_sampler(65), rep(0, n), col="red", pch=".", cex=0.5)
legend("topright",
legend=c("f_den", "samples"),
col=c("black", "red", "blue"),
pch=c("-", "."))
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.