Here's how I understand it:
x
lie in a rangeLet's assume you have a range from 0
to 100
. Given an arbitrary number from that range, what "percent" from that range does it lie in? This should be pretty simple, 0
would be 0%
, 50
would be 50%
and 100
would be 100%
.
Now, what if your range was 20
to 100
? We cannot apply the same logic as above (divide by 100) because:
20 / 100
doesn't give us 0
(20
should be 0%
now). This should be simple to fix, we just need to make the numerator 0
for the case of 20
. We can do that by subtracting:
(20 - 20) / 100
However, this doesn't work for 100
anymore because:
(100 - 20) / 100
doesn't give us 100%
. Again, we can fix this by subtracting from the denominator as well:
(100 - 20) / (100 - 20)
A more generalized equation for finding out what % x
lies in a range would be:
(x - MIN) / (MAX - MIN)
Now that we know what percent a number lies in a range, we can apply it to map the number to another range. Let's go through an example.
old range = [200, 1000]
new range = [10, 20]
If we have a number in the old range, what would the number be in the new range? Let's say the number is 400
. First, figure out what percent 400
is within the old range. We can apply our equation above.
(400 - 200) / (1000 - 200) = 0.25
So, 400
lies in 25%
of the old range. We just need to figure out what number is 25%
of the new range. Think about what 50%
of [0, 20]
is. It would be 10
right? How did you arrive at that answer? Well, we can just do:
20 * 0.5 = 10
But, what about from [10, 20]
? We need to shift everything by 10
now. eg:
((20 - 10) * 0.5) + 10
a more generalized formula would be:
((MAX - MIN) * PERCENT) + MIN
To the original example of what 25%
of [10, 20]
is:
((20 - 10) * 0.25) + 10 = 12.5
So, 400
in the range [200, 1000]
would map to 12.5
in the range [10, 20]
To map x
from old range to new range:
OLD PERCENT = (x - OLD MIN) / (OLD MAX - OLD MIN)
NEW X = ((NEW MAX - NEW MIN) * OLD PERCENT) + NEW MIN