# \donttest{
# Assuming existence of rbeta_, llbeta, grbeta, hsbeta functions
# Generate sample data from a Beta(2, 4) distribution
# (gamma=2, delta=3 in this parameterization)
set.seed(123)
true_par_beta <- c(gamma = 2, delta = 3)
sample_data_beta <- rbeta_(100, gamma = true_par_beta[1], delta = true_par_beta[2])
hist(sample_data_beta, breaks = 20, main = "Beta(2, 4) Sample")
# --- Find MLE estimates ---
start_par_beta <- c(1.5, 2.5)
mle_result_beta <- stats::optim(par = start_par_beta,
fn = llbeta,
gr = grbeta, # Use analytical gradient
method = "L-BFGS-B",
lower = c(1e-6, 1e-6), # Bounds: gamma>0, delta>=0
hessian = TRUE,
data = sample_data_beta)
# --- Compare analytical gradient to numerical gradient ---
if (mle_result_beta$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE)) {
mle_par_beta <- mle_result_beta$par
cat("\nComparing Gradients for Beta at MLE estimates:\n")
# Numerical gradient of llbeta
num_grad_beta <- numDeriv::grad(func = llbeta, x = mle_par_beta, data = sample_data_beta)
# Analytical gradient from grbeta
ana_grad_beta <- grbeta(par = mle_par_beta, data = sample_data_beta)
cat("Numerical Gradient (Beta):\n")
print(num_grad_beta)
cat("Analytical Gradient (Beta):\n")
print(ana_grad_beta)
# Check differences
cat("Max absolute difference between Beta gradients:\n")
print(max(abs(num_grad_beta - ana_grad_beta)))
} else {
cat("\nSkipping Beta gradient comparison.\n")
}
# Example with Hessian comparison (if hsbeta exists)
if (mle_result_beta$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) && exists("hsbeta")) {
num_hess_beta <- numDeriv::hessian(func = llbeta, x = mle_par_beta, data = sample_data_beta)
ana_hess_beta <- hsbeta(par = mle_par_beta, data = sample_data_beta)
cat("\nMax absolute difference between Beta Hessians:\n")
print(max(abs(num_hess_beta - ana_hess_beta)))
}
# }
Run the code above in your browser using DataLab