From 222036b3354bf154ad5e26e50c5c7eb560b6d728 Mon Sep 17 00:00:00 2001 From: Robbert van der Helm Date: Thu, 12 May 2022 01:56:07 +0200 Subject: [PATCH] Get rid of unnecessary loop in ExponentialIIR --- src/param/smoothing.rs | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/src/param/smoothing.rs b/src/param/smoothing.rs index c689247d..5509eb0d 100644 --- a/src/param/smoothing.rs +++ b/src/param/smoothing.rs @@ -274,16 +274,10 @@ impl Smoother { SmoothingStyle::Linear(_) => current + (self.step_size * steps as f32), SmoothingStyle::Logarithmic(_) => current * (self.step_size.powi(steps as i32)), SmoothingStyle::ExponentialIIR(_) => { - // TODO: Is there a way to avoid the loop here? - let mut current = current; - // TODO: We could store this `1.0 - self.step_size` on the struct, but until - // a profiler tells me that's needed this is probably fine - let target_step_size = 1.0 - self.step_size; - for _ in 0..steps { - current = current * self.step_size + (self.target * target_step_size) - } - - current + // This is the same as calculating `current = (current * step_size) + + // (target * (1 - step_size))` in a loop + let coefficient = self.step_size.powi(steps as i32); + (current * coefficient) + (self.target * (1.0 - coefficient)) } } }; @@ -404,14 +398,10 @@ impl Smoother { SmoothingStyle::Linear(_) => current + (self.step_size * steps as f32), SmoothingStyle::Logarithmic(_) => current * self.step_size.powi(steps as i32), SmoothingStyle::ExponentialIIR(_) => { - let target_step_size = 1.0 - self.step_size; - let target = self.target as f32; - let mut current = current; - for _ in 0..steps { - current = current * self.step_size + (target * target_step_size) - } - - current + // This is the same as calculating `current = (current * step_size) + + // (target * (1 - step_size))` in a loop + let coefficient = self.step_size.powi(steps as i32); + (current * coefficient) + (self.target as f32 * (1.0 - coefficient)) } } };