[Tutor] Map function

Chris Down chris at chrisdown.name
Sat Aug 10 11:39:18 CEST 2013


Hi Phil,

On 2013-08-10 16:45, Phil wrote:
> The Arduino has a map function named "map" which looks like this:
>
> map(value, 0, 1023, 0, 100)
>
> The function, in this case, takes an integer value between 0 and
> 1023 and returns a number between 0 and 100. Is there a Python
> equivalent?

The Arduino documentation[0] says that `map' is equivalent to:

    long map(long x, long in_min, long in_max, long out_min, long out_max) {
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
    }

With that in mind, you can almost copy and paste the exact same code in Python
(albeit with floor division, as in Python 3, integer division can yield
floats). Note that `//' is not strictly equivalent to C's integer division,
though.[1]

    >>> def arduino_map(x, in_min, in_max, out_min, out_max):
    ...     return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
    ...
    >>> arduino_map(50, 0, 1023, 0, 100)
    4

0: http://arduino.cc/en/Reference/map
1: http://stackoverflow.com/a/5365702/945780
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20130810/4a97dd88/attachment.pgp>


More information about the Tutor mailing list