R Under development (unstable) (2025-12-21 r89216 ucrt) -- "Unsuffered Consequences" Copyright (C) 2025 The R Foundation for Statistical Computing Platform: x86_64-w64-mingw32/x64 R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > # library(numDeriv) > # > # # 1. 数据准备 > # set.seed(123) > # n <- 1000 > # input_x <- runif(n, 0, 10) # 建议变量名也避开 x > # obs_y <- 2 + 5 * input_x + rnorm(n, 0, 1.5) > # > # # 2. 定义函数:将参数名改为完全不冲突的名称(如 my_x, my_y) > # nll_func_numeric <- function(theta_val, my_y, my_x) { > # b0 <- theta_val[1] > # b1 <- theta_val[2] > # sig <- theta_val[3] > # > # # 逻辑不变 > # y_hat <- b0 + b1 * my_x > # res <- my_y - y_hat > # n <- length(my_y) > # > # nll <- (n/2) * log(2 * pi) + n * log(sig) + sum(res^2) / (2 * sig^2) > # return(nll) > # } > # > # # 3. 估计值 > # theta_est <- c(intercept = 2.01, slope = 4.99, sigma = 1.49) > # > # # 4. 计算 Hessian > # # 现在我们可以放心地按位置传递参数了 > # hess_matrix <- hessian( > # func = nll_func_numeric, > # x = theta_est, # hessian 要求的求导中心点 > # my_y = obs_y, # 显式指定传给 nll_func_numeric 的 my_y > # my_x = input_x # 显式指定传给 nll_func_numeric 的 my_x > # ) > # > # # 5. 计算结果 > # print("--- 观测 Hessian 矩阵 ---") > # print(hess_matrix) > # > # # 协方差矩阵与标准误 > # cov_matrix <- solve(hess_matrix) > # se <- sqrt(diag(cov_matrix)) > # names(se) <- names(theta_est) > # > # cat("\n--- 参数估计的标准误 ---\n") > # print(se) > > proc.time() user system elapsed 0.14 0.01 0.14