Skip to content

Commit ff0de6d

Browse files
committed
Greatly reduces error rate (half, or 0 zero errors, depends on in/out ranges) for round-trip mapping at the same performance.
(Based on "improved_map" from ESP8266's Servo.cpp)
1 parent 13e0206 commit ff0de6d

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

Diff for: cores/esp32/WMath.cpp

+5-5
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,11 @@ long random(long howsmall, long howbig)
6666
}
6767

6868
long map(long x, long in_min, long in_max, long out_min, long out_max) {
69-
long divisor = (in_max - in_min);
70-
if(divisor == 0){
71-
return -1; //AVR returns -1, SAM returns 0
72-
}
73-
return (x - in_min) * (out_max - out_min) / divisor + out_min;
69+
const long dividend = out_max - out_min;
70+
const long divisor = in_max - in_min;
71+
const long delta = x - in_min;
72+
73+
return (delta * dividend + (divisor / 2)) / divisor + out_min;
7474
}
7575

7676
unsigned int makeWord(unsigned int w)

0 commit comments

Comments
 (0)