我有两个函数,一个是计算积分,另一个是定点方法来查找根。这是计算积分的函数:
trapezoid <- function(fun, a, b, n=100) {
h <- (b-a)/n
x <- seq(a, b, by=h)
y <- fun(x)
s <- h * (y[1]/2 + sum(y[2:n]) + y[n+1]/2)
return(s)
}
这是根发现功能:
fixedpoint <- function(fun, x0, tol=1e-03, niter=5000){
## fixed-point algorithm to find x such that fun(x) == x
## assume that fun is a function of a single variable
## x0 is the initial guess at the fixed point
xold <- x0
xnew <- fun(xold)
for (i in 1:niter) {
xold <- xnew
xnew <- fun(xold)
if ( abs((xnew-xold)) < tol )
return(xnew)
}
stop("exceeded allowed number of iterations")
}
现在我定义一个函数f f<-function(x) {x^2}
获得其集成功能h<-function(x) trapezoid(f,2,x)
最后,我想通过fixedpoint(h,2)
但是我收到了这样的错误信息:
seq.default中的错误(a,b,by = h):'to'不能是NA,NaN或 无限