use crate::root_finding::RootFinder;
pub(super) struct NewtonRaphsonRootFinder {
pub(super) x0: f64, pub(super) tolerance: f64, }
#[allow(clippy::needless_lifetimes)] impl RootFinder for NewtonRaphsonRootFinder {
fn get_init_args(&mut self) -> Box<[f64]> {
Box::from([self.x0])
}
fn get_next_args(&mut self, fx: &[f64], dfx: &[f64]) -> Box<[f64]> {
let fx = fx[0];
let dfx = dfx[0];
self.x0 -= fx / dfx;
Box::from([self.x0])
}
fn should_stop(&self, fx: &[f64], dfx: &[f64]) -> Option<Result<f64, String>> {
let fx = fx[0];
let dfx = dfx[0];
let candidate = self.x0 - fx / dfx;
if (self.x0 - candidate).abs() < self.tolerance {
return Some(Ok(candidate)); }
if dfx.abs() < f64::EPSILON {
return Some(Err("Derivative too close to zero.".to_string()));
}
None
}
}