# \donttest{
# Assuming existence of rekw, llekw, grekw, hsekw functions for EKw
# Generate sample data
set.seed(123)
true_par_ekw <- c(alpha = 2, beta = 3, lambda = 0.5)
if (exists("rekw")) {
sample_data_ekw <- rekw(100, alpha = true_par_ekw[1], beta = true_par_ekw[2],
lambda = true_par_ekw[3])
} else {
sample_data_ekw <- rgkw(100, alpha = true_par_ekw[1], beta = true_par_ekw[2],
gamma = 1, delta = 0, lambda = true_par_ekw[3])
}
hist(sample_data_ekw, breaks = 20, main = "EKw(2, 3, 0.5) Sample")
# --- Find MLE estimates ---
start_par_ekw <- c(1.5, 2.5, 0.8)
mle_result_ekw <- stats::optim(par = start_par_ekw,
fn = llekw,
gr = grekw, # Use analytical gradient for EKw
method = "BFGS",
hessian = TRUE,
data = sample_data_ekw)
# --- Compare analytical gradient to numerical gradient ---
if (mle_result_ekw$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE)) {
mle_par_ekw <- mle_result_ekw$par
cat("\nComparing Gradients for EKw at MLE estimates:\n")
# Numerical gradient of llekw
num_grad_ekw <- numDeriv::grad(func = llekw, x = mle_par_ekw, data = sample_data_ekw)
# Analytical gradient from grekw
ana_grad_ekw <- grekw(par = mle_par_ekw, data = sample_data_ekw)
cat("Numerical Gradient (EKw):\n")
print(num_grad_ekw)
cat("Analytical Gradient (EKw):\n")
print(ana_grad_ekw)
# Check differences
cat("Max absolute difference between EKw gradients:\n")
print(max(abs(num_grad_ekw - ana_grad_ekw)))
} else {
cat("\nSkipping EKw gradient comparison.\n")
}
# Example with Hessian comparison (if hsekw exists)
if (mle_result_ekw$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) && exists("hsekw")) {
num_hess_ekw <- numDeriv::hessian(func = llekw, x = mle_par_ekw, data = sample_data_ekw)
ana_hess_ekw <- hsekw(par = mle_par_ekw, data = sample_data_ekw)
cat("\nMax absolute difference between EKw Hessians:\n")
print(max(abs(num_hess_ekw - ana_hess_ekw)))
}
# }
Run the code above in your browser using DataLab