我的代码如下:了解警告消息
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的长度(我不确定其他警告消息的含义)。
有人可以帮助我理解这条信息,所以我可以纠正我被警告的任何事情吗?
呃,我想我必须把它放在循环中,除非有人知道另一种方式。但我认为这个答案最清楚地解释了警告信息,所以我会接受,但是@DWin谢谢你,你的回答总是有帮助的! – mrkb80