use mathverse_core::error::{MathError, MathResult};
use crate::derivative::{derivative, second_derivative};
pub use mathverse_numerical::{bisection, newton_raphson};
pub use mathverse_numerical::root::{
secant, false_position, brent, muller, illinois, steffensen, halley, householder, fixed_point
};
pub fn newton_raphson_auto(
f: &dyn Fn(f64) -> f64,
x0: f64,
tol: f64,
max_iter: usize,
) -> MathResult<f64> {
let mut x = x0;
for _ in 0..max_iter {
let fx = f(x);
let dfx = derivative(f, x);
if dfx.abs() < 1e-15 {
return Err(MathError::InvalidArgument("derivative is zero"));
}
let x_new = x - fx / dfx;
if (x_new - x).abs() < tol || fx.abs() < tol {
return Ok(x_new);
}
x = x_new;
}
Err(MathError::NotConverged("newton max iterations exceeded"))
}
pub fn find_critical_point(
f: &dyn Fn(f64) -> f64,
x0: f64,
tol: f64,
max_iter: usize,
) -> MathResult<f64> {
let mut x = x0;
for _ in 0..max_iter {
let dfx = derivative(f, x);
let ddfx = second_derivative(f, x);
if ddfx.abs() < 1e-15 {
return Err(MathError::InvalidArgument(
"second derivative is near zero — saddle or flat region",
));
}
let x_new = x - dfx / ddfx;
if (x_new - x).abs() < tol || dfx.abs() < tol {
return Ok(x_new);
}
x = x_new;
}
Err(MathError::NotConverged(
"critical point search exceeded max iterations",
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn newton_raphson_auto_test() {
let root = newton_raphson_auto(&|x| x * x - 4.0, 3.0, 1e-10, 100).unwrap();
assert!((root - 2.0).abs() < 1e-8);
let root2 = newton_raphson_auto(&|x| x * x * x - 8.0, 3.0, 1e-10, 100).unwrap();
assert!((root2 - 2.0).abs() < 1e-8);
}
#[test]
fn find_critical_point_test() {
let f = |x: f64| x * x * x - 3.0 * x;
let cp = find_critical_point(&f, 0.5, 1e-10, 100).unwrap();
assert!((cp - 1.0).abs() < 1e-8);
let cp2 = find_critical_point(&f, -0.5, 1e-10, 100).unwrap();
assert!((cp2 + 1.0).abs() < 1e-8);
}
#[test]
fn test_re_exported_methods() {
let root = bisection(&|x| x * x - 4.0, 1.0, 3.0, 1e-10).unwrap();
assert!((root - 2.0).abs() < 1e-8);
let root2 = newton_raphson(&|x| x * x - 4.0, &|x| 2.0 * x, 3.0, 1e-10, 100).unwrap();
assert!((root2 - 2.0).abs() < 1e-8);
let root3 = secant(&|x| x * x - 4.0, 1.0, 3.0, 1e-10, 100).unwrap();
assert!((root3 - 2.0).abs() < 1e-8);
}
}