Negative Numbers Scaling Range

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

For example, I have a set of numbers (-10, -9, 1, 4, 10) that should scale to the range [0 1], so -10 displays 0 and 10 displays 1.

The regular method for an arbitrary number of "x" will 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!!

+4
source share
2 answers

I believe id does; in your example

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

This gives

 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 

gives

 -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, 

therefore, all obtained values ​​are non-negative. In addition, an initial minimum of -10 displays to_min = 0 and an initial maximum of 10 displays to_max = 1. If this does not work in your implementation, check if you have mixed integral types and floating point types.

+3
source

Your formula works great for negative numbers.

You have:

  • from_min = -10
  • from_max = 10
  • to_min = 0
  • to_max = 1

Substituting them into the formula:

 (x - (-10)) * (1 - 0) / (10 - (-10)) + 0 

This simplifies:

 (x + 10) / 20 
+1
source

Source: https://habr.com/ru/post/1442956/


All Articles