R/Newton_Raphson.R

Defines functions Newton_Raphson

Documented in Newton_Raphson

#' Function To Compute One Dimensional Root(or Zero)
#' @param func the function for which the root is computed.
#' @param x0 *optional* an initial value
#' @param eps *optional* the precision. Default value: 1/10000000
#' @param n *optional* the number of iteration. Default value: 300
#' @description This function computes the roots or zero of a real-valued function using Newton Raphson method.
#' @examples
#' target_func1 <- function(x) {x^3 + 3*x^2 + 8*x - 10}
#' Newton_Raphson(func = target_func1, x0 = 10)
#' @export
#' @import dplyr

Newton_Raphson <- function(func, x0 = 1, epsilon = 1e-7, n = 300){

  stopifnot(is.function(func))

  delta <- 1e-7
  counter <- 1

  while(n >= counter){
    df_dx <- (func(x0 + delta) - func(x0)) / delta
    x1 <- (x0 - (func(x0) / df_dx))
    counter <- counter + 1

    if(epsilon > abs(x1 - x0)) break
    x0 <- x1
  }
  return(list(root = x1, iter = counter))
}
wasabi1989/NewtonRaphson documentation built on Nov. 14, 2019, 12:18 a.m.