You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言uniroot函数报错f.lower = f(lower) is NA问题求解

问题解决方法

错误原因

  • 矩阵索引逻辑错误:你构造的coef.mat是4行14列的矩阵,行对应四个系数项a3/a2/a1/a0,列对应14组待求解的系数。你的循环中用i遍历列数(1~14),但取数时写的coef.mat[i,j]是把i作为行索引,当i>4时行索引超出矩阵范围,返回NA,代入方程计算出来的函数值也是NA,触发f.lower = f(lower) is NA报错。
  • 冗余变量j=1没有实际作用,每组方程的四个系数直接取对应行的第i个值即可。
  • tol = 1e- 9中间有多余空格,存在语法隐患。

修正后代码

a3<- c(-1141591.0, -1192686.3,  -402424.1,  -418201.6,  -439137.0,  -654150.5,  -670148.4 , -696922.9,  -719566.3,
       -766338.7,  -794186.4 ,-812940.5,  -835722.0,  -856374.3)
a2<- c(271925.56, 284085.61,  95976.92,  99656.88, 104595.08, 156220.48, 159932.78,
       166278.36, 171602.05, 182776.53, 189310.01, 193667.54, 199019.19, 203847.51)
a1<- c(1186677.7, 1239790.1,  418324.7,  434721.3,  456480.8 , 680003.3,  696628.4 ,
       724458.4,  747992.8 , 796613.2,  825555.9,  845045.8,868723.6,  890187.6)
a0<- c(286237.4, 299037.5, 101028.3, 104902.0, 110100.1, 164442.6, 168350.3, 175029.8, 180633.7,
       192396.3, 199273.7, 203860.6, 209493.9, 214576.3)

coef.mat <- matrix(rbind(a3,a2,a1,a0), nrow = 4, byrow = TRUE)
sol.vec <- vector(length = ncol(coef.mat)) # 提前初始化向量提高效率

for(i in 1:ncol(coef.mat)){
  sol.vec[i]<-  uniroot(function(x) {
    coef.mat[1,i]*x^3 + coef.mat[2,i]*x^2 + coef.mat[3,i]*x - coef.mat[4,i]
  }, lower = -1, upper = 1, tol = 1e-9)$root 
}

运行验证

执行修正后的代码,sol.vec会输出14组根值,第一个值和你之前得到的0.2413788完全一致,后续组不会再报NA错误。

内容的提问来源于stack exchange,提问作者Mathica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 08:27:03