From ab23e8a65678d62323e023f4b9069378a3053bd2 Mon Sep 17 00:00:00 2001 From: "Dirk O. Kaar" <19971886+dok-net@users.noreply.github.com> Date: Wed, 30 Sep 2020 13:28:51 +0200 Subject: [PATCH] Greatly reduces error rate (half, or 0 zero errors, depends on in/out ranges) for round-trip mapping at the same performance. (#3655) (Based on "improved_map" from ESP8266's Servo.cpp) --- cores/esp32/WMath.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cores/esp32/WMath.cpp b/cores/esp32/WMath.cpp index abec110b..eafff903 100644 --- a/cores/esp32/WMath.cpp +++ b/cores/esp32/WMath.cpp @@ -66,11 +66,11 @@ long random(long howsmall, long howbig) } long map(long x, long in_min, long in_max, long out_min, long out_max) { - long divisor = (in_max - in_min); - if(divisor == 0){ - return -1; //AVR returns -1, SAM returns 0 - } - return (x - in_min) * (out_max - out_min) / divisor + out_min; + const long dividend = out_max - out_min; + const long divisor = in_max - in_min; + const long delta = x - in_min; + + return (delta * dividend + (divisor / 2)) / divisor + out_min; } unsigned int makeWord(unsigned int w)