给出x的函数f(x,c,d),它也取决于某些参数c和d。我想找到参数的某些值c_1,...,c_n和d_1,...,d_m的笛卡尔积的零,即x_ij,使得i的f(x_ij,c_i,d_j)= 0 = 1,...,n和j = 1,...,m。尽管不是那么关键,但我正在将Newton-Raphson算法应用于求根:
newton.raphson <- function(f, a, b, tol = 1e-5, n = 1000){
require(numDeriv) # Package for computing f'(x)
x0 <- a # Set start value to supplied lower bound
k <- n # Initialize for iteration results
# Check the upper and lower bounds to see if approximations result in 0
fa <- f(a)
if (fa == 0.0){
return(a)
}
fb <- f(b)
if (fb == 0.0) {
return(b)
}
for (i in 1:n) {
dx <- genD(func = f, x = x0)$D[1] # First-order derivative f'(x0)
x1 <- x0 - (f(x0) / dx) # Calculate next value x1
k[i] <- x1 # Store x1
# Once the difference between x0 and x1 becomes sufficiently small, output the results.
if (abs(x1 - x0) < tol) {
root.approx <- tail(k, n=1)
res <- list('root approximation' = root.approx, 'iterations' = k)
return(res)
}
# If Newton-Raphson has not yet reached convergence set x1 as x0 and continue
x0 <- x1
}
print('Too many iterations in method')
}
我感兴趣的实际功能更加复杂,但是以下示例说明了我的问题。
test.function <- function(x=1,c=1,d=1){
return(c*d-x)
}
然后对于任何给定的c_i和d_j,我都可以轻松地通过以下方式计算零
newton.raphson(function(x) test.function(x,c=c_i,d=d_j),0,1)[1]
这显然是乘积c_i * d_j。 现在,我试图定义一个函数,该函数为两个给定向量(c_1,...,c_n)和(d_1,...,d_m)查找所有组合的零。为此,我尝试定义
zeroes <- function(ci=1,dj=1){
x<-newton.raphson(function(x) test.function(x,c=ci,d=dj),0,1)[1]
return(as.numeric(x))
}
然后使用外部功能,例如
outer(c(1,2),c(1,2,3),FUN=zeroes)
不幸的是,这没有用。我收到错误消息
Error during wrapup: dims [product 6] do not match the length of object [1]
也许对于我的问题还有更好的解决方案。我很高兴有任何投入。