# \donttest{
# Generate sample data from a known GKw distribution
set.seed(123)
true_par <- c(alpha = 2, beta = 3, gamma = 1.0, delta = 0.5, lambda = 0.5)
sample_data <- rgkw(100, alpha = true_par[1], beta = true_par[2],
gamma = true_par[3], delta = true_par[4], lambda = true_par[5])
# --- Find MLE estimates (e.g., using optim) ---
start_par <- c(1.5, 2.5, 1.2, 0.3, 0.6) # Initial guess
mle_result <- stats::optim(par = start_par,
fn = llgkw,
method = "BFGS",
hessian = TRUE, # Ask optim for numerical Hessian
data = sample_data)
if (mle_result$convergence == 0) {
mle_par <- mle_result$par
print("MLE parameters found:")
print(mle_par)
# --- Compare analytical Hessian to numerical Hessian ---
# Requires the 'numDeriv' package
if (requireNamespace("numDeriv", quietly = TRUE)) {
cat("\nComparing Hessians at MLE estimates:\n")
# Numerical Hessian from numDeriv applied to negative LL function
num_hess <- numDeriv::hessian(func = llgkw, x = mle_par, data = sample_data)
# Analytical Hessian (output of hsgkw)
ana_hess <- hsgkw(par = mle_par, data = sample_data)
cat("Numerical Hessian (from numDeriv):\n")
print(round(num_hess, 4))
cat("Analytical Hessian (from hsgkw):\n")
print(round(ana_hess, 4))
# Check differences (should be small)
cat("Max absolute difference between Hessians:\n")
print(max(abs(num_hess - ana_hess)))
# Optional: Use analytical Hessian to estimate standard errors
# Ensure Hessian is positive definite before inverting
# fisher_info_analytic <- ana_hess # Hessian of negative LL
# tryCatch({
# cov_matrix <- solve(fisher_info_analytic)
# std_errors <- sqrt(diag(cov_matrix))
# cat("Std. Errors from Analytical Hessian:\n")
# print(std_errors)
# }, error = function(e) {
# warning("Could not invert analytical Hessian to get standard errors: ", e$message)
# })
} else {
cat("\nSkipping Hessian comparison (requires 'numDeriv' package).\n")
}
} else {
warning("Optimization did not converge. Hessian comparison skipped.")
}
# }
Run the code above in your browser using DataLab