# \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 = grmc, # Use analytical gradient for Mc
method = "BFGS",
hessian = TRUE,
data = sample_data_mc)
# --- Compare analytical gradient to numerical gradient ---
if (mle_result_mc$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE)) {
mle_par_mc <- mle_result_mc$par
cat("\nComparing Gradients for Mc at MLE estimates:\n")
# Numerical gradient of llmc
num_grad_mc <- numDeriv::grad(func = llmc, x = mle_par_mc, data = sample_data_mc)
# Analytical gradient from grmc
ana_grad_mc <- grmc(par = mle_par_mc, data = sample_data_mc)
cat("Numerical Gradient (Mc):\n")
print(num_grad_mc)
cat("Analytical Gradient (Mc):\n")
print(ana_grad_mc)
# Check differences
cat("Max absolute difference between Mc gradients:\n")
print(max(abs(num_grad_mc - ana_grad_mc)))
} else {
cat("\nSkipping Mc gradient comparison.\n")
}
# Example with Hessian comparison (if hsmc exists)
if (mle_result_mc$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) && exists("hsmc")) {
num_hess_mc <- numDeriv::hessian(func = llmc, x = mle_par_mc, data = sample_data_mc)
ana_hess_mc <- hsmc(par = mle_par_mc, data = sample_data_mc)
cat("\nMax absolute difference between Mc Hessians:\n")
print(max(abs(num_hess_mc - ana_hess_mc)))
}
# }
Run the code above in your browser using DataLab