Solves f(x) = 0 with a ported Numerics root finder: Brent (the default), Bisection, Secant,
or Newton-Raphson. method = "brent", "bisection", and "secant" all bracket the root on
[lower, upper], over which f must change sign; method = "newton" takes an analytic
derivative df and a first_guess instead, with the bracket optional (see below).
Usage
root_find(
f,
lower = NULL,
upper = NULL,
method = c("brent", "bisection", "secant", "newton"),
df = NULL,
first_guess = NULL,
tolerance = NULL,
max_iterations = NULL
)Arguments
- f
a function taking one number and returning one number.
- lower, upper
the bracketing interval. Required for
method"brent","bisection", and"secant". For"newton"they are optional, and it is their PRESENCE – both together – that selects the robust (bracket-aware) Newton-Raphson variant over the plain one, matching the ported class's own two entry points rather than a method sub-argument.- method
one of
"brent"(the default),"bisection","secant", or"newton".- df
the analytic derivative of
f, a function taking one number and returning one number. Required for, and only used by,method = "newton".- first_guess
the running root Bisection and Newton-Raphson seed themselves with (the bracket only seeds their initial step direction / bracket maintenance). Required for
method = "bisection"andmethod = "newton"; unused by"brent"and"secant", which pick their own starting point off the bracket.- tolerance
the convergence tolerance on the root.
NULL, the default, leaves the ported solver's own default (1e-8) in force; the value is not restated here, so a change to it lands in one place.- max_iterations
the iteration cap; the search raises an error if it is reached.
NULL, the default, leaves the ported solver's own default (1000) in force.
Examples
root_find(function(x) x^2 - 2, lower = 0, upper = 2)
#> [1] 1.414214
root_find(function(x) x^2 - 2, lower = 0, upper = 4, method = "bisection", first_guess = 1)
#> [1] 1.414214
root_find(function(x) x^3 - x - 1, lower = -1, upper = 5, method = "secant")
#> [1] 1.324718
root_find(function(x) x^2 - 2, method = "newton", df = function(x) 2 * x, first_guess = 1)
#> [1] 1.414214