我正在尝试创建包围功能并在R中使用以下代码:
y<-function(x){x^2+2*x}
a<--1
b<-1
alpha<-(sqrt(5)-1)/2
e<-0.001
bracketing<-function(f, a, b, c, top, result){
if (f(a) > f(b)) {
return(result)
}
else if(top==1){
c<-b + alpha*(b-a)
}
result[top,]<-c(a, b, c)
if (f(b) < f(c)) {
a<-b
b<-c
c<-b + alpha*(b-a)
}
else if (f(b) > f(c)) {
a<-b
b<-c
c<-b + alpha*(b-a)
}
result<-bracketing(f, a, b, c, top=top+1, result)
return(result)
}
result<-data.frame(a=rep(NA), b=rep(NA), c=rep(NA))
result<-bracketing(y, NA, NA, NA, 1, result)
我在if函数中收到此错误消息:
Error in if (f(a) > f(b)) { : missing value where TRUE/FALSE needed
我该如何预防?