Search code examples
pythonrangescale

Scaling a number between a certain range to that of another in python


Is there a method by which a number between the range of lets say (a, b) can be scaled to a different range of lets say (p, q)?

In my case, I have a number between in the range of 0 to 1 i.e (0, 1) and wanna scale it such that it lies in the range of -1 to 1 i.e.(-1, 1).

Example -:

# 1 will remain 1 if scaled.
scale(1, (0, 1), (-1, 1)) # => Returns 1
# 0.5 will be scaled to 0.
scale(0.5, (0, 1), (-1, 1)) # => Returns 0
# 0 will be scaled to -1.
scale(0, (0, 1), (-1, 1)) # => Returns -1

I was able to find a few related threads on -: Based on mathematical formula and does not mention any pythonic way of doing so and secondly I am not able to distinguish between the upper and lower limits and max(x), min(x)


Solution

  • Try this:

    def scale(x, srcRange, dstRange):
        return (x-srcRange[0])*(dstRange[1]-dstRange[0])/(srcRange[1]-srcRange[0])+dstRange[0]
    

    Of course, each range must be given in the form of (min, max).

    In your example, one of the ranges is given the form of (max, min).