Learn R Programming

comphy (version 1.0.5)

roots_secant: Secant method for roots

Description

Find the zero of a function of one variable, \(f(x)\), given a starting value close to the zero, using the secant method.

Usage

roots_secant(
  fn,
  x0,
  x1,
  imax = 1e+06,
  ftol = 1e-09,
  message = TRUE,
  logg = FALSE,
  ...
)

Value

A numeric value, the zero of the function (or, equivalently, the root of the equation \(f(x)=0\)).

Arguments

fn

A function of one variable. If the function includes variables, these will have to be passed as additional variables, using the same names in the function's definition (see examples).

x0, x1

Two numeric variables. The initial guesses starting the algorithm.

imax

A positive integer. The maximum number of iterations of the algorithm. The default value is 1e6, although convergence is normally obtained with a number of iterations much smaller than imax. imax is important to stop search in those cases in which the algorithm gets stuck in endless loops (non-convergence).

ftol

A real small number. The algorithm stops when \(|f(x)| < ftol\). Default value is 1e-09.

message

A logical variable to state whether messages about the root and the error have to be printed. The default is for the messages to be printed (message=TRUE).

logg

A logical variable to state whether information on the series of approximating roots is printed (TRUE) or not (FALSE). Default is for such information not to be printed (FALSE).

...

Parameters passed to function `fn`, if needed.

Details

Finding the zero of \(f(x)\) is equivalent to finding the roots of the equation: $$ f(x) = 0 $$ The algorithm used is essentially a reworking of Newton-Raphson, where the first derivative is replaced by a finite difference computed with values x0 and x1. Thus two values, x0 and x1, needs to be selected to start the procedure. The convergence for this method is in general achieved faster than with the bisection method and slightly less fast than with Newton-Raphson. The algorithm can fail to converge when the secant in one of the iterations is parallel to the x axis.

Examples

Run this code
# The quadratic equation x^2-5*x+6=0 has two roots, 2 and 3
fn <- function(x) return(x^2-5*x+6)

# Find root 2, starting from two points at the left of 2
x0 <- 0
x1 <- 1
x <- roots_secant(fn,x0,x1)
print(x)

# Find root 3 (no message printing)
x0 <- 5
x1 <- 4
x <- roots_secant(fn,x0,x1,message=FALSE)
print(x)

# Function with a parameter f(x) = exp(kx) - 2
fn <- function(x,k=2) return(exp(k*x)-2)

# Solution of exp(2x)-2=0 is log(2)/2
x0 <- 0
x1 <- 1
x <- roots_secant(fn,x0,x1,k=2)
print(log(2)/2)

Run the code above in your browser using DataLab