refactor newtons_method

This commit is contained in:
Simon Gardling 2022-03-23 20:56:04 -04:00
parent fd82c71652
commit c4c29328b6
3 changed files with 35 additions and 53 deletions

View File

@ -36,6 +36,7 @@ tar = "0.4.38"
ruzstd = { git = "https://github.com/KillingSpark/zstd-rs.git" }
serde_json = "1.0.79"
tracing = "0.1.32"
itertools = "0.10.3"
[build-dependencies]
shadow-rs = "0.11.0"

View File

@ -226,9 +226,6 @@ impl FunctionEntry {
self.output.invalidate_derivative();
}
let do_extrema = settings.extrema && (min_max_changed | self.output.extrema.is_none());
let do_roots = settings.roots && (min_max_changed | self.output.roots.is_none());
self.min_x = min_x;
self.max_x = max_x;
@ -281,12 +278,12 @@ impl FunctionEntry {
};
// Calculates extrema
if do_extrema {
if settings.extrema && (min_max_changed | self.output.extrema.is_none()) {
self.output.extrema = self.newtons_method_helper(threshold, 1);
}
// Calculates roots
if do_roots {
if settings.roots && (min_max_changed | self.output.roots.is_none()) {
self.output.roots = self.newtons_method_helper(threshold, 0);
}

View File

@ -1,4 +1,5 @@
use eframe::egui::plot::Value as EguiValue;
use itertools::Itertools;
use serde_json::Value as JsonValue;
#[cfg(not(target_arch = "wasm32"))]
@ -183,30 +184,14 @@ pub fn newtons_method(
threshold: f64, range: std::ops::Range<f64>, data: Vec<EguiValue>, f: &dyn Fn(f64) -> f64,
f_1: &dyn Fn(f64) -> f64,
) -> Vec<f64> {
let mut output_list: Vec<f64> = Vec::new();
let mut last_ele_option: Option<EguiValue> = None;
for ele in data.iter() {
if last_ele_option.is_none() {
last_ele_option = Some(*ele);
continue;
}
// if `ele.y` is NaN, just continue iterating
if ele.y.is_nan() {
continue;
}
let last_ele_y = last_ele_option.unwrap().y; // store this here as it's used multiple times
// if `last_ele.y` is NaN, continue iterating
if last_ele_y.is_nan() {
continue;
}
if last_ele_y.signum() != ele.y.signum() {
data.iter()
.tuples()
.filter(|(prev, curr)| !(prev.y.is_nan() | curr.y.is_nan()))
.map(|(prev, curr)| {
if prev.y.signum() != curr.y.signum() {
// actual start of newton's method
let x = {
let mut x1: f64 = last_ele_option.unwrap().x;
let mut x1: f64 = prev.x;
let mut x2: f64;
let mut fail: bool = false;
loop {
@ -231,13 +216,12 @@ pub fn newtons_method(
}
};
if !x.is_nan() {
output_list.push(x);
return x;
}
}
last_ele_option = Some(*ele);
}
output_list
f64::NAN
})
.filter(|x| !x.is_nan())
.collect()
}
// Returns a vector of length `max_i` starting at value `min_x` with resolution