【问题标题】:How can I run my Newton's method in this case?在这种情况下如何运行我的牛顿法?
【发布时间】: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


【解决方案1】:

希望我的回答对您有所帮助: 如果你尝试?genD,你会读到:

用法

genD(func, x, method="Richardson",
               method.args=list(), ...)
## Default S3 method: genD(func, x, method="Richardson",
  method.args=list(), ...) Arguments

func 一个函数,它的第一个(向量)参数用作 参数向量。 x func 的参数向量第一个参数。

在 R 文档的底部有这个例子:

例子

func <- function(x){c(x[1], x[1], x[2]^2)}
z <- genD(func, c(2,2,5))

因此,您的代码的问题是您需要使用向量作为 f 的参数:

f <- function(c){   (exp(c[1]) - 2) ^ c[2] }

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 = c(x0,n))$D[1]

      #get the x1
      x1 <- x0 - (f(c(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)

如果我运行,我的输出是:

$`root approximation` [1] 0.6931375

$iteration [1] 15

最好的!

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2020-05-19
    • 1970-01-01
    • 2016-07-27
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多