簡體   English   中英

在這種情況下如何運行我的牛頓法?

[英]How can I run my Newton's method in this case?

有一個函數,如: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”,沒有默認值

我怎么能弄明白呢? 感謝您的幫助!

我希望你覺得我的回答有幫助:如果你嘗試?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

最好的事物!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM