diff --git a/NonLinearEquationSolvers/Rust/src/errors.rs b/NonLinearEquationSolvers/Rust/src/errors.rs new file mode 100644 index 0000000000000000000000000000000000000000..3d9dd79ebd79c7371da289d96d6785d7077fd272 --- /dev/null +++ b/NonLinearEquationSolvers/Rust/src/errors.rs @@ -0,0 +1,22 @@ +#[derive(Debug, Clone)] +pub struct InvariantError { + msg: String, +} + +impl InvariantError { + pub fn new(msg: String) -> Self { + InvariantError { msg } + } +} + +impl From<&str> for InvariantError { + fn from(msg: &str) -> Self { + InvariantError::new(msg.to_string()) + } +} + +impl From<String> for InvariantError { + fn from(msg: String) -> Self { + InvariantError::new(msg) + } +} diff --git a/NonLinearEquationSolvers/Rust/src/lib.rs b/NonLinearEquationSolvers/Rust/src/lib.rs index 027ffb5f8d582f8d9b14d319ad0c143e60584f2e..abf805308500b54bda7044e5e629949682b5a013 100644 --- a/NonLinearEquationSolvers/Rust/src/lib.rs +++ b/NonLinearEquationSolvers/Rust/src/lib.rs @@ -2,4 +2,5 @@ #[macro_use] extern crate hamcrest2; +pub mod errors; pub mod loop_monoliths; diff --git a/NonLinearEquationSolvers/Rust/src/loop_monoliths.rs b/NonLinearEquationSolvers/Rust/src/loop_monoliths.rs index 9a39f014435f4c077ef78a4a88d6888eff11a3fd..d521e799574f5f04383bc4b78efe1b3616ecaf72 100644 --- a/NonLinearEquationSolvers/Rust/src/loop_monoliths.rs +++ b/NonLinearEquationSolvers/Rust/src/loop_monoliths.rs @@ -1,18 +1,9 @@ +use super::errors::InvariantError; + const EPSILON: f64 = 10e-8; const MAX_ITERATIONS: u64 = 100; const ONE_HALF: f64 = 0.5; -#[derive(Debug, Clone)] -pub struct InvariantError { - pub msg: String, -} - -impl InvariantError { - fn new(msg: String) -> Self { - InvariantError { msg } - } -} - /// Compute a solution to f using the bisection method /// /// a0 = a @@ -45,11 +36,8 @@ pub fn bisection( for n in 1..MAX_ITERATIONS { if f(b_n) < 0.0 { - return Err(InvariantError::new(format!( - "$f(b_{} = {}) < 0$", - (n - 1), - b_n - ))); + let message = format!("$f(b_{} = {}) < 0$", (n - 1), b_n); + return Err(message.into()); } x_n = ONE_HALF * (a_n + b_n); @@ -103,9 +91,7 @@ pub fn regula_falsi( x_n = a_n - ((a_n - b_n) / (f(a_n) - f(b_n))) * f(a_n); if !x_n.is_finite() { - return Err(InvariantError::new( - format!("$f(a_n) - f(b_n) == 0$",), - )); + return Err(InvariantError::from("$f(a_n) - f(b_n) == 0$")); } if f(x_n) * f(a_n) > 0.0 { @@ -151,9 +137,7 @@ pub fn secant( x_n - ((x_n - x_n_minus_1) / (f(x_n) - f(x_n_minus_1))) * f(x_n); if !next_x_n.is_finite() { - return Err(InvariantError::new(format!( - "$f(x_n) - f(x_nm1) == 0$", - ))); + return Err(InvariantError::from("$f(x_n) - f(x_nm1) == 0$")); } x_n_minus_1 = x_n; @@ -182,7 +166,7 @@ pub fn newton( let next_x_n = x_n - (f(x_n) / df(x_n)); if !next_x_n.is_finite() { - return Err(InvariantError::new(format!("$df(x_n) == 0$"))); + return Err(InvariantError::from("$df(x_n) == 0$")); } if (x_n - next_x_n).abs() < EPSILON {