From 58829022edadf981326fad0f92bad4e2385fa89e Mon Sep 17 00:00:00 2001 From: "Dirk O. Kaar" Date: Tue, 21 Jan 2020 11:28:14 +0100 Subject: [PATCH] Fix "improved_map" from Servo.cpp and use this is in core implementation. Greatly reduces error rate (half, or 0 zero errors, depends on in/out ranges) for round-trip mapping at the same performance. --- cores/esp8266/WMath.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cores/esp8266/WMath.cpp b/cores/esp8266/WMath.cpp index 1f0c8d7db..2cc20b9f5 100644 --- a/cores/esp8266/WMath.cpp +++ b/cores/esp8266/WMath.cpp @@ -70,11 +70,11 @@ long secureRandom(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) {