Search code examples
mathscale

Scaling range of values with negative numbers


How can I scale a set of values to fit a new range if they include negative numbers?

For example, I have a set of numbers (-10, -9, 1, 4, 10) which have to scaled to a range [0 1], such that -10 maps to 0, and 10 maps to 1.

The regular method for an arbitrary number 'x' would be: (x - from_min) * (to_max - to_min) / (from_max - from_min) + to_min

but this does not work for negative numbers. Any help is appreciated. Thanks!!


Solution

  • I believe id does; in your example,

    from_min = -10,
    from_max = 10,
    to_max = 1,
    to_min = 0.
    

    This yields

    to_max - to_min = 1,
    from_max - from_min = 20;
    

    So using the formula

    x -> (x - from_min) * (to_max - to_min) / (from_max - from_min) + to_min
       = (x - from_min) * 1 / 20 + 0
       = (x - from_min) / 20
    

    yields

    -10 -> (-10 + 10) / 20 = 0 / 20,
    -9 -> (-9 + 10) / 20 = 1 / 20,
    1 -> (1 + 10) / 20 = 11 / 20,
    4 -> (4 + 10) / 20 = 14 / 20,
    10 -> (10 + 10) / 20 = 20 / 20,
    

    so all the resulting values are nonnegative. Furthermore, the original minimum -10 maps to to_min = 0 and the original maximum 10 maps to to_max = 1. If this doesn't work in your implementation, check if you mixed up integral types and floating-point types.