From f89389b4c227b7e0d9e36efc56c280b4d8c01b35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me?= Date: Sat, 25 Mar 2023 23:04:48 +0100 Subject: [PATCH] Ok fixed now --- src/main.rs | 7 +++++-- src/univariate_solvers.rs | 12 +++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index c774bb1..a4e4b3c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,8 +24,11 @@ fn main() { let x0 : f64 = 1.0; let tol : f64 = 1e-10; let max_iter : u32 = 100; + let dx_num : f64 = 1e-6; let x_mathematica = -3.26650043678562449167148755288; let x_newton = univariate_solvers::newton_solve(&(fct as fn(f64) -> f64), &(dfct as fn(f64) -> f64), x0, tol, max_iter); - println!("Mathematica : x = {}", x_mathematica); - println!("Newton's method : x = {}", x_newton); + let x_newton_num: f64 = univariate_solvers::newton_solve_num(&(fct as fn(f64) -> f64), x0, tol, dx_num, max_iter); + println!("Mathematica : x = {}", x_mathematica); + println!("Newton's method : x = {}", x_newton); + println!("Newton's method (num) : x = {}", x_newton_num); } diff --git a/src/univariate_solvers.rs b/src/univariate_solvers.rs index 2db983d..a6b03ce 100644 --- a/src/univariate_solvers.rs +++ b/src/univariate_solvers.rs @@ -5,7 +5,9 @@ /// @param tol tolerance /// @param max_iter maximum number of iterations /// @return solution -pub fn newton_solve f64, F2: Fn(f64) -> f64>(f : &F, df : &F2, x0 : f64, tol : f64, max_iter : u32) -> f64 { +pub fn newton_solve(f : F, df : F2, x0 : f64, tol : f64, max_iter : u32) -> f64 + where F : Fn(f64) -> f64, F2 : Fn(f64) -> f64 +{ let mut x: f64 = x0; let mut dx: f64; let mut fx: f64; @@ -33,7 +35,11 @@ pub fn newton_solve f64, F2: Fn(f64) -> f64>(f : &F, df : &F2, x0 /// @param tol tolerance /// @param max_iter maximum number of iterations /// @return solution -pub fn newton_solve_num f64>(f : &F, x0 : f64, tol : f64, dx_num : f64, max_iter : u32) -> f64 { - return newton_solve(f, &((|x: f64| (f(x + dx_num) - f(x - dx_num))/(2.0*dx_num)) as fn(f64) -> f64), x0, tol, max_iter); +pub fn newton_solve_num(f : F, x0 : f64, tol : f64, dx_num : f64, max_iter : u32) -> f64 +where F : Fn(f64) -> f64 +{ + return newton_solve(&f, |x: f64| { + (f(x + dx_num) - f(x - dx_num))/(2.0*dx_num) + }, x0, tol, max_iter); }