Normalizing one range of values to another range of values.

To add another generic answer.
If you want to map the linear range [A..B] to [C..D], you can apply the following steps:
Shift the range so the lower bound is 0. (subract A from both bounds:
[A..B] -> [0..B-A]
Scale the range so it is [0..1]. (divide by the upper bound):
[0..B-A] -> [0..1]
Scale the range so it has the length of the new range which is D-C. (multiply with D-C):
[0..1] ->  [0..D-C]
Shift the range so the lower bound is C. (add C to the bounds):
[0..D-C] -> [C..D]
Combining this to a single formula, we get:
       (D-C)*(X-A)
X' =   -----------  + C
          (B-A)
Eg :

Normalizing a range of 0.5 ----> 1.0   to 0 ------> 1
 A=0.5, B=1, C=0, D=1 you get:
       (X-0.5)
X' =   ------- = 2X-1
        (0.5)
Note, if you have to convert a lot of X to X', you can change the formula to:
       (D-C)         C*B - A*D
X' =   ----- * X  +  ---------  
       (B-A)           (B-A)

Comments

Popular posts from this blog

Bounding Box in PIL (Python Image Library)

Dictionary vs KeyValuePair vs Struct - C#

Rendering order and Z-sorting