root_find
root_find(
f,
lower=None,
upper=None,
method='brent',
df=None,
first_guess=None,
tolerance=None,
max_iterations=None,
)Find a root of a user-written function.
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).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| f | callable | A function taking one number and returning one number. | required |
| lower | float | 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. |
None |
| upper | float | 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. |
None |
| method | ('brent', 'bisection', 'secant', 'newton') | The root finder to use. | "brent" |
| df | callable | The analytic derivative of f, a function taking one number and returning one number. Required for, and only used by, method = "newton". |
None |
| first_guess | float | The running root Bisection and Newton-Raphson seed themselves with (the bracket only seeds their initial step direction / bracket maintenance). Required for method = "bisection" and method = "newton"; unused by "brent" and "secant", which pick their own starting point off the bracket. |
None |
| tolerance | float | The convergence tolerance on the root. Left unset, the ported solver’s own default (1e-8) applies; the value is not restated here, so a change to it lands in one place. | None |
| max_iterations | int | The iteration cap; the search raises if it is reached. Left unset, the ported solver’s own default (1000) applies. | None |
Returns
| Name | Type | Description |
|---|---|---|
| float | The root. |
Examples
>>> import corehydropy as ch
>>> round(ch.root_find(lambda x: x**2 - 2, lower=0, upper=2), 6)
1.414214
>>> round(ch.root_find(lambda x: x**2 - 2, lower=0, upper=4,
... method="bisection", first_guess=1), 6)
1.414214
>>> round(ch.root_find(lambda x: x**3 - x - 1, lower=-1, upper=5, method="secant"), 5)
1.32472
>>> round(ch.root_find(lambda x: x**2 - 2, method="newton",
... df=lambda x: 2 * x, first_guess=1), 6)
1.414214