0

我的代码如下:

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 的长度(我不确定其他警告消息的含义) .

有人可以帮助我理解此消息,以便我可以更正我被警告的任何内容吗?

4

2 回答 2

1

You can trigger errors so that traceback() will be available for debugging of warnings, athough that is mprobably not needed here;

 options(warn=2) # usual setting is 1

Type this to see what your function is seeing for the arguments:

> c(a=0, b=5,m= results[,1])
  a   b  m1  m2  m3  m4  m5  m6  m7 
  0   5   9  17  33  65 129 257 513

So that's where the first warning about seq( , , by=.) getting an excessively long argument comes from, (since h will be as long as the 'm' argument was. I think that mostly explains the other warnings as well. I do not know of a way to get the warn() mechanism to skip the first or up to the n-th waring but if you dropped into the browser you could do that:

?browser

You could also search SO for best practices for [r] debugging

于 2013-04-13T17:11:05.493 回答
1

你确定你得到了预期的输出吗?无论我怎么读?seq,看起来“by”参数应该是一个数字,而不是你的例子中的向量。这就是您收到讨厌警告的原因,因为h不是单个数字而是向量。

你得到的序列seq(a,b,h)很奇怪:

> seq(a,b,h)
[1] 0.00000000 0.31250000 0.31250000 0.23437500 0.15625000 0.09765625 0.05859375
[8] 4.37500000 2.50000000

我认为seq它是为生成单调序列而设计的,但是从你的例子中得出的结果既不是单调的,也没有任何意义......

你真的确定最终的结果是你所期望的吗?无论如何,这看起来像是对 的滥用seq,除非我遗漏了什么。

于 2013-04-13T17:29:35.283 回答