【发布时间】:2019-06-20 08:27:18
【问题描述】:
有一个类似的功能: y = (e^x - 2)^n
x 是未知数,因为 n = 2,3,4,...,8 现在我想用NR方法找到这个函数的根(初始x为0)。
如果 n 是固定值,我知道如何编写 NR 方法,这是我的原始 NR 代码:
NR <- function(f, x0, tol = 1e-5, ite = 1000){
require(numDeriv) #call the package for computing dx
k <- ite
for (i in 1:ite){
#calculate dx
dx <- genD(func = f, x = x0)$D[1]
#get the x1
x1 <- x0 - (f(x0) / dx)
k[i] <- x1
if(abs(x1 - x0) < tol){
root <- x1
re <- list('root approximation' = root, 'iteration' = length(k))
return(re)
}
x0 <- x1
}
print('Outside the upper iteration')
}
现在我重写我的函数:
f <- function(x, n){
(exp(x) - 2) ^ n
}
如果我想为不同的 n 输出每个根,我想我应该在循环“for (i in 1:ite)”之前添加另一个循环 于是我重写了我的NR功能代码:
NR <- function(f, x0, tol = 1e-5, ite = 1000){
require(numDeriv) #call the package for computing dx
k <- ite
for(n in 2:8){
for (i in 1:ite){
#calculate dx
dx <- genD(func = f, x = x0)$D[1]
#get the x1
x1 <- x0 - (f(x0, n) / dx)
k[i] <- x1
if(abs(x1 - x0) < tol){
root <- x1
re <- list('root approximation' = root, 'iteration' = length(k))
return(re)
}
x0 <- x1
}
print('Outside the upper iteration')
}
}
但是当我运行 NR(f,0) 时,R 向我显示错误是: func(x, ...) 中的错误:缺少参数“n”,没有默认值
我该如何解决这个问题? 感谢您的帮助!
【问题讨论】:
-
旁注:你应该几乎总是使用
library,而不是require。当包不可用时,后者永远不会停止跟踪代码,这几乎不是预期的。如果你想使用require,那么保存它的返回值并用它做一些事情(例如,优雅地失败,使用其他函数等)。参考:stackoverflow.com/a/51263513/3358272
标签: r newtons-method