我的代碼如下:瞭解警告消息
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