uniroots: Locate zeros (roots) of a function

View source: R/rootfinding_optimization.R

unirootsR Documentation

Locate zeros (roots) of a function

Description

Find the x-axis values where f(x) = 0. This can also be used to find the intersections between two functions, i.e., f1(x) - f2(x) = 0, see examples.

Usage

uniroots(f, xlim, tol = .Machine[["double.eps"]]^0.25, expected_nroots = 1)

Arguments

f

Function.

xlim

A numeric vector of length 2. The search interval.

tol

A numeric value. The convergence tolerance.

expected_nroots

Maximum number of roots, i.e., the interval xlim is split into this number of contiguous sections and each is checked for the presence of a root

Value

A list where each element is an object returned from uniroot or of class "try-error" (see try), or NULL.

See Also

uniroot and uniroot.all.

Examples

# Locate roots of a function
f <- function(x) -1 + x^2
xt <- seq(-1.5, 1.5, by = 0.1)
plot(xt, f(xt), type = "l")
abline(h = 0, col = "gray")

r <- uniroots(
  f = f,
  xlim = c(-10, 10),
  expected_nroots = 2
)

for (i in seq_along(r)) {
  abline(v = r[[i]][["root"]], col = "red")
}

# Locate intersections between two functions
a2 <- 4
f1 <- function(x) sin(2 * x)
f2 <- function(x, a) cos(1 - a * x)

xt <- seq(-1, 1, by = 0.1)
plot(xt, f1(xt), type = "l")
lines(xt, f2(xt, a2), col = "gray")

r <- uniroots(
  f = function(x, a = a2) f1(x) - f2(x, a = a),
  xlim = c(-1, 1),
  expected_nroots = 3
)

for (i in seq_along(r)) {
  abline(v = r[[i]][["root"]], col = "red")
}


DrylandEcology/rSW2utils documentation built on Dec. 9, 2023, 10:44 p.m.