Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Templated map() function #46

Open
thiagohersan opened this issue Nov 13, 2013 · 2 comments
Open

Templated map() function #46

thiagohersan opened this issue Nov 13, 2013 · 2 comments
Assignees

Comments

@thiagohersan
Copy link

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;
}
@Lauszus
Copy link

Lauszus commented Nov 26, 2013

I think this would be really useful as well!

@sandeepmistry sandeepmistry transferred this issue from arduino/Arduino Sep 16, 2019
@PaulStoffregen
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants