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 function = scalar_fn!(|x| c(-2.0) + x * x);
let solver: Newton = Newton::default();
let initial_guess = 2.0_f64;
let report = solver.solve(&function, initial_guess).unwrap();
assert!((report.root - 2.0_f64.sqrt()).abs() < 1e-12);Implementations§
Source§impl Newton<AutoDiffSingle>
impl Newton<AutoDiffSingle>
Source§impl<D: DerivatorSingleVariable> Newton<D>
impl<D: DerivatorSingleVariable> Newton<D>
Sourcepub const fn from_derivator(derivator: D) -> Self
pub const 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.
use multicalc::numerical_derivative::AutoDiffSingle;
use multicalc::root_finding::Newton;
const D: AutoDiffSingle = AutoDiffSingle::new();
const SOLVER: Newton<AutoDiffSingle> = Newton::from_derivator(D);Sourcepub const fn with_xtol(self, xtol: D::Scalar) -> Self
pub const fn with_xtol(self, xtol: D::Scalar) -> Self
Sets the step-size tolerance (relative: compared against xtol × (1 + |x|)).
Sourcepub const fn with_ftol(self, ftol: D::Scalar) -> Self
pub const fn with_ftol(self, ftol: D::Scalar) -> Self
Sets the residual tolerance: the solver stops when |f(x)| ≤ ftol.
Sourcepub const fn with_max_iterations(self, max_iterations: usize) -> Self
pub const fn with_max_iterations(self, max_iterations: usize) -> Self
Sets the maximum number of iterations.
Sourcepub const fn with_backtracking(self, backtracking: bool) -> Self
pub const 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.