ArduinoCore-API icon indicating copy to clipboard operation
ArduinoCore-API copied to clipboard

Templated map() function

Open thiagohersan opened this issue 11 years ago • 2 comments

Hello !

Apologies if this is a duplicate, but I couldn't find any previous discussions on github about it.

Is there a reason why map() isn't templated to provide maximum awesomeness??

Something as simple as this, would get rid of surprises when trying to use map() to scale to [0,1]:

template<class T>
T map(T x, T in_min, T in_max, T out_min, T out_max)
{
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

thiagohersan avatar Nov 13 '13 00:11 thiagohersan

I think this would be really useful as well!

Lauszus avatar Nov 26 '13 23:11 Lauszus

FWIW, we've been using a C++ template for map() on Teensy for quite some time. It turned to be quite a bit more complicated than the code above. Ultimately we ended up with 2 templates using type_traits and std:enable_if. When the input "x" is any integer type, you want to convert all 5 inputs to signed long. If you skip that step, problems with numerical range come up. When the input "x" is any floating point type, you want to convert the other 4 inputs to that type, so the whole thing is done in the same numerical precision as the input number.

Another problem that comes up is the min() and max() macros conflict with C++ min() and max(), which come along with including type_traits. Ultimately 2 versions of min & max were needed, depending on whether compiling C or C++.

Here's the code, if anyone wants it. https://github.com/PaulStoffregen/cores/blob/e888ebd01a9f5ef71b6998c7b338c5e2b555467a/teensy4/wiring.h#L44

This also has the integer-only map() algorithm which solves issue #51

PaulStoffregen avatar Oct 31 '20 10:10 PaulStoffregen