brentZero: Brent's local root search

View source: R/brent.R

brentZeroR Documentation

Brent's local root search

Description

Brent's local root search

Usage

brentZero(
  f,
  interval,
  lower = NA_real_,
  upper = NA_real_,
  f_lower = NULL,
  f_upper = NULL,
  extendInt = "no",
  tol = 1e-08,
  maxiter = 500L,
  trace = 0L
)

Arguments

f

The function for which the root is sought.

interval

A length-2 vector containing the end-points of the search interval

lower

Scalar: the lower end point of the search interval. Not necessary if interval is provided.

upper

Scalar: the upper end point of the search interval. Not necessary if interval is provided.

f_lower

Scalar: same as f(upper). Passing this value saves time if f(lower) is slow to compute and is known.

f_upper

Scalar: same as f(lower).

extendInt

Character:

"no"

Do not extend the interval (default).

"yes"

Attempt to extend both ends until a sign change is found.

"upX"

Assumes the function is increasing around the root and extends upward if needed.

"downX"

Assumes the function is decreasing around the root and extends downward if needed.

This behavior mirrors that of [uniroot()].

tol

Small positive scalar: convergence tolerance. The search stops when the bracket size is smaller than 2 * .Machine$double.eps * abs(x) + tol, or if the function evaluates to zero at the candidate root.

maxiter

Positive integer: the maximum number of iterations before stopping.

trace

Integer: 0, 1, or 2. Controls the verbosity of the output. trace = 0 produces no output, trace = 1 reports the starting and final results, and trace = 2 provides detailed iteration-level output.

Value

A list with the following elements:

root

Location of the root.

f.root

Function value at the root.

iter

Total iteration count used.

init.it

Number of initial extendInt iterations if there were any; NA otherwise.

estim.prec

Estimate of the final bracket size.

Examples

f <- function (x, a) x - a
str(uniroot(f, c(0, 1), tol = 0.0001, a = 1/3))
uniroot(function(x) cos(x) - x, lower = -pi, upper = pi, tol = 1e-9)$root

# This function is faster than the base R uniroot, and this is the primary
# reason why it was written in C++
system.time(replicate(1000, { shift <- runif(1, 0, 2*pi)
  uniroot(function(x) cos(x+shift) - x, lower = -pi, upper = pi)
}))
system.time(replicate(1000, { shift <- runif(1, 0, 2*pi)
  brentZero(function(x) cos(x+shift) - x, lower = -pi, upper = pi)
}))
# Roughly twice as fast

smoothemplik documentation built on Aug. 22, 2025, 1:11 a.m.