So I have a function which always returns a number from range <0;99> (i.e. 0, 1, ... 99 - integers).
What would be the best way to correctly map those numbers to range <-1.0;1.0>?
0 would be -1.0 of course and 99 would be 1.0. How to calculate the numbers between?
Use a linear mapping:
y = ((x / 99.0) * 2) - 1
How it works:
You can of course combine the steps ((x / 99.0) * 2) into a single division if you wish. I just split it up for clarity.
Don't do scaling manually; it takes far too much squinting at the math to figure out what's really intended. Use a helper function.
def scale(val, src, dst):
"""
Scale the given value from the scale of src to the scale of dst.
"""
return ((val - src[0]) / (src[1]-src[0])) * (dst[1]-dst[0]) + dst[0]
print scale(0, (0.0, 99.0), (-1.0, +1.0))
print scale(1, (0.0, 99.0), (-1.0, +1.0))
print scale(99, (0.0, 99.0), (-1.0, +1.0))
I've found this to be one of the more useful functions to have in any language; you can tell what the scale() calls do at a glance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With