rejection_sampling: Rejection Sampling

Description Usage Arguments Details Value See Also Examples

View source: R/rejection_sampling.R

Description

The rejection_sampling function operator creates a function that draws samples from a given probability density function.

Usage

1
rejection_sampling(f_den, g_den, g, M)

Arguments

f_den

S3 object of class Density; the probability density to construct the sampler for.

g_den

S3 object of class Density; the probability density for the sampler given in g.

g

R function with single numeric argument; the random number generator that draws samples from the density function g_den.

M

strictly positive numeric scalar; satisfies f(x) <= M*g(x) for all numeric scalar inputs x.

Details

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.

Value

A function taking a single numeric scalar argument n, returning n f-den distributed random numbers.

See Also

Density for more information about densities.

Examples

 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("-", "."))

hericks/KDE documentation built on Aug. 22, 2020, 12:04 a.m.