# Example 1
# To sample from a standard normal distribution \( f(x) \sim \mathcal{N}(0,1) \),
# first build the proposal using \code{build_proposal()}
modes_norm = 0
f_norm <- function(x) { 1 / sqrt(2 * pi) * exp(-0.5 * x^2) }
h_norm <- function(x) { log(f_norm(x)) }
h_prime_norm <- function(x) { -x }
normal_proposal = build_proposal(lower = -Inf, upper = Inf, mode = modes_norm,
f = f_norm, h = h_norm, h_prime = h_prime_norm, steps = 1000)
# Generate samples from the standard normal distribution
sample_normal <- build_sampler(normal_proposal)
hist(sample_normal(100), main = "Normal Distribution Samples")
# Example 2
# Let's consider a bimodal distribution composed of two normal distributions:
# The first normal distribution N(0,1) with weight p = 0.3,
# and the second normal distribution N(4,1) with weight q = 0.7.
f_bimodal <- function(x) {
0.3 * (1 / sqrt(2 * pi) * exp(-0.5 * (x - 0)^2)) +
0.7 * (1 / sqrt(2 * pi) * exp(-0.5 * (x - 4)^2))
}
# Define the modes of the bimodal distribution
modes_bimodal <- c(0.00316841, 3.99942)
# Build the proposal for the bimodal distribution
bimodal_proposal = build_proposal(f = f_bimodal, modes = modes_bimodal,
lower = -Inf, upper = Inf, steps = 1000)
# Create the sampling function using \code{build_sampler()}
sample_bimodal <- build_sampler(bimodal_proposal)
# Generate and plot samples from the bimodal distribution
bimodal_samples <- sample_bimodal(1000)
hist(bimodal_samples, breaks = 30, main = "Bimodal Distribution Samples")
# Create the truncated sampling function using
# \code{build_sampler()} with truncation bounds [-0.5, 6]
truncated_bimodal_proposal <- build_proposal(f = f_bimodal,
modes = modes_bimodal, lower = -0.5, upper = 6, steps = 1000)
# Create the sampling function using \code{build_sampler()}
sample_truncated_bimodal <- build_sampler(truncated_bimodal_proposal)
# Generate and plot samples from the truncated bimodal distribution
truncated_sample <- sample_truncated_bimodal(1000)
hist(truncated_sample, breaks = 30, main = "Truncated Bimodal Distribution Samples")
Run the code above in your browser using DataLab