Closed microbit-carlos closed 2 years ago
Let's go for microbit.scale(value, from=(low, high), to=(low, high)
.
But also need to decide if the function clamps as well as scales, or just scales?
I was originally thinking we should clamp, as a common use-case would be to map accelerometer get x/y/z values almost as if they were pitch/roll. In those cases if the board is calmly rotated it normally returns values up to around 1000 mg (1g), but can often be slightly larger than that (and much larger if the board is shaken).
However, the main goal of this function is two scale a value to a different range, so if the value is already out of the "from" range it should be the same for the "to" range. A good example is when converting between celsius and fahrenheit, as you normally would do this as microbit.scale(value, from=(0, 100), to=(32, 212))
, and clamping would prevent this from working correctly.
Moreover, the user can still clamp the output value of this function if needed. So no need to do this inside the scale function.
Implemented in 0f0766fd7a8a95ead2ea1aa7512ae8780e99f0a9
Note that it does allow negative scaling, which could be useful. Eg map 0 to 100 into 0 to -50.
A function like this is quite useful to be able to map inputs an outputs with different value ranges. For example the output from one sensor to an LED brightness value, sound level, or sound effect attribute.
Arduino, and MakeCode have a
map()
function with the same argument order, so it'd be good to follow the convention:Although it's tempting to try to improve it:
Would that be better? I personally don't feel strongly either way.
Options for the name
map()
andrange()
are already taken in Python, so we shouldn't shadow themtransform()
is a tiny bit longer and not very clear what it might bescale()
seems like a good wordWhere to we put the function?
microbit
module, as many programmes dofrom microbit import *
math
module, but that would divert from the CPython implementation and we should probably avoid thatumath
is probably also undesirable?