View source: R/rootfinding_optimization.R
uniroots | R Documentation |
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.
uniroots(f, xlim, tol = .Machine[["double.eps"]]^0.25, expected_nroots = 1)
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 |
A list where each element is an object
returned from uniroot
or of
class "try-error"
(see try
), or NULL
.
uniroot
and
uniroot.all
.
# 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")
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.