【问题标题】:How to avoid uniroot error that stops the loop [duplicate]如何避免停止循环的uniroot错误[重复]
【发布时间】:2021-12-03 15:41:01
【问题描述】:

我在循环中运行uniroot 函数,但遇到错误并且代码停止。代码如下;

func <-function(f) -a*b/c*0.5*d*e^2 + (d/f-1)*g*sin(h*(pi/180))-i
dat <- data.frame(a = c(0.99,0.99,0.99),
                  b = c(0.1986572,0.1986572,0.1986572),
                  c = c(237.5,237.5,237.5),
                  d = c(1028.372, 1028.711, 1028.372),
                  e = c(2.46261, 2.986461, 2.46261),
                  f = c(-1,-1,-1),
                  g = c(9.8,9.8,9.8),
                  h = c(-54.97964, -51.65978, -54.97964),
                  i = c(0.03699588, -0.0375189, 0.03699588))

for(j in 1:length(dat$a)){
   a <- dat$a[j]
   b <- dat$b[j]
   c <- dat$c[j]
   d <- dat$d[j]
   e <- dat$e[j]
   #f: this should be solved by uniroot
   g <- dat$g[j]
   h <- dat$h[j]
   i <- dat$i[j]
   sol <- uniroot(func,c(0, 2000),extendInt = "yes") 
   dat$f[j] <- sol$root
   print(j)
}

运行上面的代码,遇到下面的错误:

[1] 1
Error in uniroot(func, c(0, 2000), extendInt = "yes") : 
      no sign change found in 1000 iterations

代码停在j=1,并没有走到j=2&3。因此,dat$f显示

> dat$f
[1] 1526.566   -1.000   -1.000

我的目标是当uniroot 在给定的j 中遇到错误时,将NA 放入dat$f[j],并在最后继续循环。

如果可行,dat$f[1]dat$f[3] 应该使用上述数据框具有相同的值 (=1526.566)。

请告诉我如何处理 uniroot 错误。

(这篇文章已被修改为包含可供所有人重现的代码,如suggested in my last post

【问题讨论】:

标签: r try-catch uniroot


【解决方案1】:

尝试扩大区间的范围。例如:

sol <- uniroot(func, c(0, 5000), extendInt = "yes") 

您的代码停止,因为在您定义的uniroot 范围内没有找到解决方案

【讨论】:

  • 这行得通,非常感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2019-06-24
  • 2017-11-01
  • 2013-06-27
相关资源
最近更新 更多