pub struct Newton<D: DerivatorSingleVariable = AutoDiffSingle> { /* private fields */ }Expand description
A scalar Newton solver, optionally damped by a backtracking line search.
The derivative defaults to exact autodiff via AutoDiffSingle (Dual numbers).
Any DerivatorSingleVariable can be passed to from_derivator
to use a different backend, including finite differences.
With backtracking off (the default), each step is x − f(x)/f′(x). With it on,
the step length is halved until |f| decreases, rescuing iterates that would otherwise
overshoot the root.
Cost per iteration: 1 function evaluation + 1 derivative evaluation
(+ ≤ MAX_BACKTRACK extra function evaluations when backtracking is on).
§Examples
use multicalc::root_finding::Newton;
use multicalc::scalar::c;
use multicalc::scalar_fn;
// f(x) = x² − 2, root at √2 ≈ 1.41421356
let f = scalar_fn!(|x| c(-2.0) + x * x);
let solver: Newton = Newton::default();
let report = solver.solve(&f, 2.0_f64).unwrap();
assert!((report.root - 2.0_f64.sqrt()).abs() < 1e-12);Implementations§
Source§impl<D: DerivatorSingleVariable> Newton<D>
impl<D: DerivatorSingleVariable> Newton<D>
Sourcepub fn from_derivator(derivator: D) -> Self
pub fn from_derivator(derivator: D) -> Self
Builds a solver with the given derivator and default settings:
tolerances of 30 × EPSILON, budget of 100 iterations, backtracking off.
Sourcepub fn with_xtol(self, xtol: D::Scalar) -> Self
pub fn with_xtol(self, xtol: D::Scalar) -> Self
Sets the step-size tolerance (relative: compared against xtol × (1 + |x|)).
Sourcepub fn with_ftol(self, ftol: D::Scalar) -> Self
pub fn with_ftol(self, ftol: D::Scalar) -> Self
Sets the residual tolerance: the solver stops when |f(x)| ≤ ftol.
Sourcepub fn with_max_iterations(self, max_iterations: usize) -> Self
pub fn with_max_iterations(self, max_iterations: usize) -> Self
Sets the maximum number of iterations.
Sourcepub fn with_backtracking(self, backtracking: bool) -> Self
pub fn with_backtracking(self, backtracking: bool) -> Self
Enables or disables backtracking: when on, each Newton step is halved until |f|
decreases or the safeguard runs out. Off by default.
Sourcepub fn solve<F: ScalarFn>(
&self,
f: &F,
x0: D::Scalar,
) -> Result<RootReport<D::Scalar>, SolveError>
pub fn solve<F: ScalarFn>( &self, f: &F, x0: D::Scalar, ) -> Result<RootReport<D::Scalar>, SolveError>
Finds a root of f starting from x0.
Returns the root estimate and termination reason, or an error:
NonFinite if f or its derivative is non-finite,
Linalg wrapping Singular if the derivative
is zero, or DidNotConverge if the budget is exhausted.