我的代码如下:
m<-c(9,17,33,65,129,257,513)
results<-matrix(,7,5)
results[,1]<-m
#methods
trap<-function(a,b,m,func)
{
h=(b-a)/(m-1)
x<-seq(a,b,h)
y<-function(x) {
z<-eval(parse(text=func))
return(z)
}
result<-h*(0.5* y(x[1]) + sum(y(x[2:(length(x)-1)]))+ 0.5*y(x[length(x)]) )
result
}
当我运行以下命令时:trap(0,5,results[,1],"x^2")
我得到了预期的输出,但我也得到了一条令人讨厌的警告消息:
Warning messages:
1: In if (n < 0L) stop("wrong sign in 'by'
argument") : the condition has length > 1 and only the first element
will be used
2: In if (n > .Machine$integer.max) stop("'by' argument
is much too small") : the condition has length > 1 and only the
first element will be used
3: In 0L:n : numerical expression has 7
elements: only the first used
4: In (0L:n) * by : longer object
length is not a multiple of shorter object length
5: In if (by > 0)
pmin(x, to) else pmax(x, to) : the condition has length > 1 and only
the first element will be used
所以我开始试图理解发生了什么,似乎一切都指向这一点:x<-seq(a,b,h)
但我的序列永远不应该是负数,它应该总是创建一个大于 1 的长度(我不确定其他警告消息的含义) .
有人可以帮助我理解此消息,以便我可以更正我被警告的任何内容吗?