# \donttest{
# Assuming existence of rekw, grekw, hsekw functions for EKw distribution
# Generate sample data from a known EKw distribution
set.seed(123)
true_par_ekw <- c(alpha = 2, beta = 3, lambda = 0.5)
# Use rekw if it exists, otherwise use rgkw with gamma=1, delta=0
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")
# --- Maximum Likelihood Estimation using optim ---
# Initial parameter guess
start_par_ekw <- c(1.5, 2.5, 0.8)
# Perform optimization (minimizing negative log-likelihood)
# Use method="L-BFGS-B" for box constraints if needed (all params > 0)
mle_result_ekw <- stats::optim(par = start_par_ekw,
fn = llekw, # Use the EKw neg-log-likelihood
method = "BFGS", # Or "L-BFGS-B" with lower=1e-6
hessian = TRUE,
data = sample_data_ekw)
# Check convergence and results
if (mle_result_ekw$convergence == 0) {
print("Optimization converged successfully.")
mle_par_ekw <- mle_result_ekw$par
print("Estimated EKw parameters:")
print(mle_par_ekw)
print("True EKw parameters:")
print(true_par_ekw)
} else {
warning("Optimization did not converge!")
print(mle_result_ekw$message)
}
# --- Compare numerical and analytical derivatives (if available) ---
# Requires 'numDeriv' package and analytical functions 'grekw', 'hsekw'
if (mle_result_ekw$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) &&
exists("grekw") && exists("hsekw")) {
cat("\nComparing Derivatives at EKw MLE estimates:\n")
# Numerical derivatives of llekw
num_grad_ekw <- numDeriv::grad(func = llekw, x = mle_par_ekw, data = sample_data_ekw)
num_hess_ekw <- numDeriv::hessian(func = llekw, x = mle_par_ekw, data = sample_data_ekw)
# Analytical derivatives (assuming they return derivatives of negative LL)
ana_grad_ekw <- grekw(par = mle_par_ekw, data = sample_data_ekw)
ana_hess_ekw <- hsekw(par = mle_par_ekw, data = sample_data_ekw)
# Check differences
cat("Max absolute difference between gradients:\n")
print(max(abs(num_grad_ekw - ana_grad_ekw)))
cat("Max absolute difference between Hessians:\n")
print(max(abs(num_hess_ekw - ana_hess_ekw)))
} else {
cat("\nSkipping derivative comparison for EKw.\n")
cat("Requires convergence, 'numDeriv' package and functions 'grekw', 'hsekw'.\n")
}
# }
Run the code above in your browser using DataLab