From 79da65792bc969a45623baf139f4a9eea0d79043 Mon Sep 17 00:00:00 2001 From: Simon Gardling Date: Wed, 9 Mar 2022 22:36:34 -0500 Subject: [PATCH] stop newton iteration if outside display range --- src/function.rs | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/function.rs b/src/function.rs index 3ce972c..e0954f9 100644 --- a/src/function.rs +++ b/src/function.rs @@ -308,13 +308,25 @@ impl FunctionEntry { let x = { let mut x1: f64 = last_ele.unwrap().x; let mut x2: f64; + let mut fail: bool = false; for _ in 0..NEWTON_LOOPS { x2 = x1 - (self.function.get(x1) / self.function.derivative(x1)); + if !(self.min_x..self.max_x).contains(&x2) { + fail = true; + break; + } x1 = x2; } - x1 + + match fail { + true => f64::NAN, + false => x1, + } }; - root_list.push(Value::new(x, self.function.get(x))); + + if !x.is_nan() { + root_list.push(Value::new(x, self.function.get(x))); + } } last_ele = Some(*ele); } @@ -343,14 +355,26 @@ impl FunctionEntry { let x = { let mut x1: f64 = last_ele.unwrap().x; let mut x2: f64; + let mut fail: bool = false; for _ in 0..NEWTON_LOOPS { x2 = x1 - (self.function.derivative(x1) / self.function.get_derivative_2(x1)); + if !(self.min_x..self.max_x).contains(&x2) { + fail = true; + break; + } x1 = x2; } - x1 + + match fail { + true => f64::NAN, + false => x1, + } }; - extrama_list.push(Value::new(x, self.function.get(x))); + + if !x.is_nan() { + extrama_list.push(Value::new(x, self.function.get(x))); + } } last_ele = Some(*ele); }