diff --git a/src/function.rs b/src/function.rs index e735f90..ae47da9 100644 --- a/src/function.rs +++ b/src/function.rs @@ -46,9 +46,6 @@ pub struct FunctionEntry { extrema: bool, } -// How many times should newton's method iterate? -const NEWTON_LOOPS: usize = 50; - impl FunctionEntry { // Creates Empty Function instance pub fn empty() -> Self { @@ -291,6 +288,7 @@ impl FunctionEntry { // Finds roots fn roots(&mut self) { + let resolution: f64 = (self.pixel_width as f64 / (self.max_x - self.min_x).abs()) as f64; let mut root_list: Vec = Vec::new(); let mut last_ele: Option = None; for ele in self.output.back.as_ref().unwrap().iter() { @@ -312,12 +310,17 @@ impl FunctionEntry { let mut x1: f64 = last_ele.unwrap().x; let mut x2: f64; let mut fail: bool = false; - for _ in 0..NEWTON_LOOPS { + loop { x2 = x1 - (self.function.get(x1) / self.function.derivative(x1)); if !(self.min_x..self.max_x).contains(&x2) { fail = true; break; } + + if (x2 - x1).abs() < resolution { + break; + } + x1 = x2; } @@ -338,6 +341,7 @@ impl FunctionEntry { // Finds extrema fn extrema(&mut self) { + let resolution: f64 = (self.pixel_width as f64 / (self.max_x - self.min_x).abs()) as f64; let mut extrama_list: Vec = Vec::new(); let mut last_ele: Option = None; for ele in self.output.derivative.as_ref().unwrap().iter() { @@ -359,13 +363,18 @@ impl FunctionEntry { let mut x1: f64 = last_ele.unwrap().x; let mut x2: f64; let mut fail: bool = false; - for _ in 0..NEWTON_LOOPS { + loop { x2 = x1 - (self.function.derivative(x1) / self.function.get_derivative_2(x1)); if !(self.min_x..self.max_x).contains(&x2) { fail = true; break; } + + if (x2 - x1).abs() < resolution { + break; + } + x1 = x2; }