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
This commit is contained in:
IanSC
2022-02-01 19:26:52 +08:00
committed by GitHub
parent dafdc05249
commit 5be3ff74ea

View File

@ -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) { 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 run = in_max - in_min;
const long divisor = in_max - in_min; if(run == 0){
const long delta = x - in_min; log_e("map(): Invalid input range, min == max");
if(divisor == 0){ return -1; // AVR returns -1, SAM returns 0
log_e("Invalid map 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) uint16_t makeWord(uint16_t w)