# \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 = if (exists("grbeta")) grbeta else NULL,
method = "L-BFGS-B",
lower = c(1e-6, 1e-6), # Bounds: gamma>0, delta>=0
hessian = TRUE, # Ask optim for numerical Hessian
data = sample_data_beta)
# --- Compare analytical Hessian to numerical Hessian ---
if (mle_result_beta$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) &&
exists("hsbeta")) {
mle_par_beta <- mle_result_beta$par
cat("\nComparing Hessians for Beta at MLE estimates:\n")
# Numerical Hessian of llbeta
num_hess_beta <- numDeriv::hessian(func = llbeta, x = mle_par_beta, data = sample_data_beta)
# Analytical Hessian from hsbeta
ana_hess_beta <- hsbeta(par = mle_par_beta, data = sample_data_beta)
cat("Numerical Hessian (Beta):\n")
print(round(num_hess_beta, 4))
cat("Analytical Hessian (Beta):\n")
print(round(ana_hess_beta, 4))
# Check differences
cat("Max absolute difference between Beta Hessians:\n")
print(max(abs(num_hess_beta - ana_hess_beta)))
# Optional: Use analytical Hessian for Standard Errors
# tryCatch({
# cov_matrix_beta <- solve(ana_hess_beta) # ana_hess_beta is already Hessian of negative LL
# std_errors_beta <- sqrt(diag(cov_matrix_beta))
# cat("Std. Errors from Analytical Beta Hessian:\n")
# print(std_errors_beta)
# }, error = function(e) {
# warning("Could not invert analytical Beta Hessian: ", e$message)
# })
} else {
cat("\nSkipping Beta Hessian comparison.\n")
cat("Requires convergence, 'numDeriv' package, and function 'hsbeta'.\n")
}
# }
Run the code above in your browser using DataLab