Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map numbers in range <0;99> to range <-1.0;1.0>?

Tags:

python

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?

like image 346
Richard Knop Avatar asked Nov 11 '10 13:11

Richard Knop


2 Answers

Use a linear mapping:

y = ((x / 99.0) * 2) - 1

How it works:

  • Divide by 99: This normalizes the range from [0, 99] to [0, 1].
  • Multiply by 2: This increases the range to [0, 2].
  • Subtract 1: This is a translation which gives [-1, 1].

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.

like image 161
Mark Byers Avatar answered Oct 12 '22 02:10

Mark Byers


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.

like image 26
Glenn Maynard Avatar answered Oct 12 '22 02:10

Glenn Maynard