如何避免停止循环的 uniroot 错误
How to avoid uniroot error that stops the loop
我在循环中运行 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 错误。
(此 post 已修改为包括代码以便每个人都可以重现,如 )
尝试扩大间隔的范围。例如:
sol <- uniroot(func, c(0, 5000), extendInt = "yes")
您的代码停止,因为在您定义的范围内uniroot
没有找到解决方案
我在循环中运行 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 错误。
(此 post 已修改为包括代码以便每个人都可以重现,如
尝试扩大间隔的范围。例如:
sol <- uniroot(func, c(0, 5000), extendInt = "yes")
您的代码停止,因为在您定义的范围内uniroot
没有找到解决方案