Skip to content

Commit c265ddb

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 9f8d27f commit c265ddb

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

cores/arduino/WMath.cpp

+6-3
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,12 @@ long random(long howsmall, long howbig)
4949
return random(diff) + howsmall;
5050
}
5151

52-
long map(long x, long in_min, long in_max, long out_min, long out_max)
53-
{
54-
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
52+
long map(long x, long in_min, long in_max, long out_min, long out_max) {
53+
const long dividend = out_max - out_min;
54+
const long divisor = in_max - in_min;
55+
const long delta = x - in_min;
56+
57+
return (delta * dividend + (divisor / 2)) / divisor + out_min;
5558
}
5659

5760
unsigned int makeWord(unsigned int w) { return w; }

0 commit comments

Comments
 (0)