(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
X is your value. in_min is the minimum value of X. If you subtract that minimum value from X you re-map X into the range it can be.
For instance if X can be between 10 and 20 the in_min would be 10 and in the in_max would be 20. X will be somewhere between the two. Say X is 14. So X is 4 more than the minimum, or X - in_min = 4.
That gives you how far (in quanta of X) into the range you are.
out_max - out_min gives you the range of the output in the same way. If you want to map to 200 to 300, say, the range between the two is 100.
The same with in_max and in_min - it gives the size of the input range - 10 in this case (20 - 10 = 10).
So you now have some values:
- 4 is how far through the input range you are
- 100 is how big the output range is
- 10 is how big the input range is
Multiply the first two together and divide by the third and you get how far through the output range the input is. You could also do it the other way around - divide the input offset (4) by the input size (10) to get the percentage (in the range 0 to 1) that you are through the input. Multiply that percentage by the size of the output range to get how far through the output you are. The way it is done avoids the use of any floating point values which makes it faster.
So 4 * 100 = 400. 400 / 10 = 40. Or, 4 / 10 = 0.4, 0.4 * 100 = 40.
Then you just add to that the output minimum values which just gives it an offset. 40 + 200 = 240.
map(14, 10, 20, 200, 300) == 240.
To reiterate the steps:
- 14 - 10 = 4 (input offset)
- 20 - 10 = 10 (input range)
- 300 - 200 = 100 (output range)
- 4 * 100 = 400 (percentage of input range
- 400 / 10 = 40 applied to output range)
- 200 + 40 = 240 (add output offset)