Skip to content

Commit

Permalink
Merge pull request #7027 from dok-net/wmath_map
Browse files Browse the repository at this point in the history
Fix WMath's map() implementation for inverse/round-trip mapping
  • Loading branch information
earlephilhower authored Feb 9, 2020
2 parents 50a491b + cd5cbae commit 56b90a2
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions cores/esp8266/WMath.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

1 comment on commit 56b90a2

@TD-er
Copy link
Contributor

@TD-er TD-er commented on 56b90a2 Feb 10, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will give a divide by zero when in_max == in_min
I think it makes sense to just return out_min if the input range is the 0.

Please sign in to comment.