[Tutor] Map function
Phil
phil_lor at bigpond.com
Sat Aug 10 12:18:30 CEST 2013
On 10/08/13 19:39, Chris Down wrote:
> 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
>
Thanks Chris,
I had come up with something similar, but it was more complex without
the // operator, which led me to thinking that perhaps Python had a
similar map function built in.
Anyway, thanks again my curiosity has been satisfied.
--
Regards,
Phil
More information about the Tutor
mailing list