# \donttest{
# Assuming existence of rmc, llmc, grmc, hsmc functions for Mc distribution
# Generate sample data
set.seed(123)
true_par_mc <- c(gamma = 2, delta = 3, lambda = 0.5)
sample_data_mc <- rmc(100, gamma = true_par_mc[1], delta = true_par_mc[2],
lambda = true_par_mc[3])
hist(sample_data_mc, breaks = 20, main = "Mc(2, 3, 0.5) Sample")
# --- Find MLE estimates ---
start_par_mc <- c(1.5, 2.5, 0.8)
mle_result_mc <- stats::optim(par = start_par_mc,
fn = llmc,
gr = if (exists("grmc")) grmc else NULL,
method = "BFGS",
hessian = TRUE, # Ask optim for numerical Hessian
data = sample_data_mc)
# --- Compare analytical Hessian to numerical Hessian ---
if (mle_result_mc$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) &&
exists("hsmc")) {
mle_par_mc <- mle_result_mc$par
cat("\nComparing Hessians for Mc at MLE estimates:\n")
# Numerical Hessian of llmc
num_hess_mc <- numDeriv::hessian(func = llmc, x = mle_par_mc, data = sample_data_mc)
# Analytical Hessian from hsmc
ana_hess_mc <- hsmc(par = mle_par_mc, data = sample_data_mc)
cat("Numerical Hessian (Mc):\n")
print(round(num_hess_mc, 4))
cat("Analytical Hessian (Mc):\n")
print(round(ana_hess_mc, 4))
# Check differences (monitor sign consistency)
cat("Max absolute difference between Mc Hessians:\n")
print(max(abs(num_hess_mc - ana_hess_mc)))
# Optional: Use analytical Hessian for Standard Errors
# tryCatch({
# cov_matrix_mc <- solve(ana_hess_mc) # ana_hess_mc is already Hessian of negative LL
# std_errors_mc <- sqrt(diag(cov_matrix_mc))
# cat("Std. Errors from Analytical Mc Hessian:\n")
# print(std_errors_mc)
# }, error = function(e) {
# warning("Could not invert analytical Mc Hessian: ", e$message)
# })
} else {
cat("\nSkipping Mc Hessian comparison.\n")
cat("Requires convergence, 'numDeriv' package, and function 'hsmc'.\n")
}
# }
Run the code above in your browser using DataLab