# \donttest{
# Assuming existence of rkw, grkw, hskw functions for Kw distribution
# Generate sample data from a known Kw distribution
set.seed(123)
true_par_kw <- c(alpha = 2, beta = 3)
sample_data_kw <- rkw(100, alpha = true_par_kw[1], beta = true_par_kw[2])
hist(sample_data_kw, breaks = 20, main = "Kw(2, 3) Sample")
# --- Maximum Likelihood Estimation using optim ---
# Initial parameter guess
start_par_kw <- c(1.5, 2.5)
# Perform optimization (minimizing negative log-likelihood)
# Use method="L-BFGS-B" for box constraints (params > 0)
mle_result_kw <- stats::optim(par = start_par_kw,
fn = llkw, # Use the Kw neg-log-likelihood
method = "L-BFGS-B",
lower = c(1e-6, 1e-6), # Lower bounds > 0
hessian = TRUE,
data = sample_data_kw)
# Check convergence and results
if (mle_result_kw$convergence == 0) {
print("Optimization converged successfully.")
mle_par_kw <- mle_result_kw$par
print("Estimated Kw parameters:")
print(mle_par_kw)
print("True Kw parameters:")
print(true_par_kw)
} else {
warning("Optimization did not converge!")
print(mle_result_kw$message)
}
# --- Compare numerical and analytical derivatives (if available) ---
# Requires 'numDeriv' package and analytical functions 'grkw', 'hskw'
if (mle_result_kw$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) &&
exists("grkw") && exists("hskw")) {
cat("\nComparing Derivatives at Kw MLE estimates:\n")
# Numerical derivatives of llkw
num_grad_kw <- numDeriv::grad(func = llkw, x = mle_par_kw, data = sample_data_kw)
num_hess_kw <- numDeriv::hessian(func = llkw, x = mle_par_kw, data = sample_data_kw)
# Analytical derivatives (assuming they return derivatives of negative LL)
ana_grad_kw <- grkw(par = mle_par_kw, data = sample_data_kw)
ana_hess_kw <- hskw(par = mle_par_kw, data = sample_data_kw)
# Check differences
cat("Max absolute difference between gradients:\n")
print(max(abs(num_grad_kw - ana_grad_kw)))
cat("Max absolute difference between Hessians:\n")
print(max(abs(num_hess_kw - ana_hess_kw)))
} else {
cat("\nSkipping derivative comparison for Kw.\n")
cat("Requires convergence, 'numDeriv' package and functions 'grkw', 'hskw'.\n")
}
# }
Run the code above in your browser using DataLab