簡體   English   中英

使用 newton-raphson 方法找到正數的根,R

[英]Finding the root of positive number using newton-raphson-method, R

所以我有以下 function,它使用 Newton-raphson 方法找到 function 的根。 我認為我的問題相對簡單:我希望 function 使用 newton raphson 方法找到給定正數的平方根 幫助?

# FUNCTION: 
newton <- function(f, delta = 0.0000001, x_0 = 2, n=1000){
  h = 0.0000001
  i = 1; x1 = x_0
  p = numeric(n)
  while (i <= n) { #while i is less than or equal to n(1000), continue iterations
    df.dx = (f(x_0 + h) - f(x_0)) / h # 
    x1 = (x_0 - (f(x_0) / df.dx)) # output of original guess minus (f(x)/f´(x)) (formula for root finding)
    p[i] = x1 # counts iteration so we don't exceed 1000
    i = i+1 # same as ^
    if (abs(x1 - x_0) < delta) break # if output is less than delta: end iteration. Otherwise continue. (x1-x_0=if new value is below our threshold, stop)
    x_0 = x1
  }
  return(p[1: (i-1)]) #
}

############## TEST ###############
func1 <- function(x){
  x^5 - 7
}

newton(func1)

#VARIABLES are
#f = the function we input 
#delta = the accuracy threashold we are willing to accept 
#x_0 = our initial guess
#n = the number of iterations
#h = the distance from X1 to X0,this value much little ,the root much #closed.
#abs is a sys

一個可能的解決方案:

newton <- function(f, delta = 0.0000001, x_0 = 2, n=1000){
  h = 0.0000001
  i = 1; x1 = x_0
  p = numeric(n)
  while (i <= n) { #while i is less than or equal to n(1000), continue iterations
    df.dx = (f(x_0 + h) - f(x_0)) / h # 
    x1 = (x_0 - (f(x_0) / df.dx)) # output of original guess minus (f(x)/f´(x)) (formula for root finding)
    p[i] = x1 # counts iteration so we don't exceed 1000
    i = i+1 # same as ^
    if (abs(x1 - x_0) < delta) break # if output is less than delta: end iteration. Otherwise continue. (x1-x_0=if new value is below our threshold, stop)
    x_0 = x1
  }
  return(list(result = x1, iterations = p[1:i-1]))
}

nthrootsub <- function(input, nth, x){ x^nth - input}

nthroot <- function(input, nth) {newton(function(x) nthrootsub(input, nth, x))}

############## TEST ###############

10^(1/5)
#[1] 1.584893

nthroot(10,5)
#$result
#[1] 1.584893

#$iterations
#[1] 1.725000 1.605878 1.585435 1.584894 1.584893 1.584893

暫無
暫無

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

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