From 5be3ff74ea6057c7ee35fcc0cd60defb82786ec3 Mon Sep 17 00:00:00 2001 From: IanSC <8453489+IanSC@users.noreply.github.com> Date: Tue, 1 Feb 2022 19:26:52 +0800 Subject: [PATCH] Unnecessary operation removed from map() in WMath.cpp (#6218) * Unneccesary Operation Removed (A) extra operation not needed and incorrect: wrong by 0.5 but happens to be thrown out ( delta * dividend + (divisor / 2) ) / divisor delta * dividend divisor = ---------------- + ----------- divisor 2 * divisor = delta * dividend / divisor + 1/2 (B) check first before doing other computations (C) changed to rise/run, easier for future maintainer since it's closer to equation of a line (D) before: mult, shift, add, div, add now: mult, div, add (E) error message easier to trace where thrown * Update WMath.cpp forgot to change variable name --- cores/esp32/WMath.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/cores/esp32/WMath.cpp b/cores/esp32/WMath.cpp index bb75fc8a..931ac966 100644 --- a/cores/esp32/WMath.cpp +++ b/cores/esp32/WMath.cpp @@ -67,14 +67,14 @@ long random(long howsmall, long howbig) } long map(long x, long in_min, long in_max, long out_min, long out_max) { - const long dividend = out_max - out_min; - const long divisor = in_max - in_min; - const long delta = x - in_min; - if(divisor == 0){ - log_e("Invalid map input range, min == max"); - return -1; //AVR returns -1, SAM returns 0 + const long run = in_max - in_min; + if(run == 0){ + log_e("map(): Invalid input range, min == max"); + return -1; // AVR returns -1, SAM returns 0 } - return (delta * dividend + (divisor / 2)) / divisor + out_min; + const long rise = out_max - out_min; + const long delta = x - in_min; + return (delta * rise) / run + out_min; } uint16_t makeWord(uint16_t w)