# \donttest{
# Assuming existence of rkw, llkw, grkw, hskw functions for Kw
# Generate sample data
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")
# --- Find MLE estimates ---
start_par_kw <- c(1.5, 2.5)
mle_result_kw <- stats::optim(par = start_par_kw,
fn = llkw,
gr = grkw, # Use analytical gradient for Kw
method = "L-BFGS-B", # Recommended for bounds
lower = c(1e-6, 1e-6),
hessian = TRUE,
data = sample_data_kw)
# --- Compare analytical gradient to numerical gradient ---
if (mle_result_kw$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE)) {
mle_par_kw <- mle_result_kw$par
cat("\nComparing Gradients for Kw at MLE estimates:\n")
# Numerical gradient of llkw
num_grad_kw <- numDeriv::grad(func = llkw, x = mle_par_kw, data = sample_data_kw)
# Analytical gradient from grkw
ana_grad_kw <- grkw(par = mle_par_kw, data = sample_data_kw)
cat("Numerical Gradient (Kw):\n")
print(num_grad_kw)
cat("Analytical Gradient (Kw):\n")
print(ana_grad_kw)
# Check differences
cat("Max absolute difference between Kw gradients:\n")
print(max(abs(num_grad_kw - ana_grad_kw)))
} else {
cat("\nSkipping Kw gradient comparison.\n")
}
# Example with Hessian comparison (if hskw exists)
if (mle_result_kw$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) && exists("hskw")) {
num_hess_kw <- numDeriv::hessian(func = llkw, x = mle_par_kw, data = sample_data_kw)
ana_hess_kw <- hskw(par = mle_par_kw, data = sample_data_kw)
cat("\nMax absolute difference between Kw Hessians:\n")
print(max(abs(num_hess_kw - ana_hess_kw)))
}
# }
Run the code above in your browser using DataLab