From time to time, programmers need to map a range of values to another range, consider these examples:

Example 1: Changing random numbers scope/range: A randomization library generates random decimal numbers in the range of [0,1], but you actually need an integer random number between 100 and 1000.

Example 2: You have a range of data between –100 and 100, and you want to make gray scale values between 0 and 255 for them in a reversed fashion (-100 should be mapped to 255, and 100 should be mapped to 0).

Now you know what I’m talking about, and I’m pretty sure you’ve encountered such a situation in your life as a programmer. So what is a general solution for this problem? Let’s see!

To find a solution, I’m going to pick the second example and draw a mapping diagram for it. In this example, we have a min number of –100 that should be mapped to 255, and a max number of 100 that should be mapped to 0, like this:

Since we have a linear map for our ranges, we can draw a straight line between these 2 points. Now we have to find a Y for any given X on this line. For example, I would like to know for X=O, what will the mapped Y be?

Now that we have converted the question to a math

linear interpolationproblem, the rest is as easy as a few basic math operations!

When we have 2 points on a line, the straight line equation can be retrieved easily by this formula:

( x2 – x1 ) ( y – y1 ) = ( y2 – y1 ) ( x – x1 )

If we enter [x1,y1] and [x2,y2] in the formula above, we’ll have an equation in the Ax + By = C format, but we’re not interested in this. The only thing we need to do here is to enter the 5th parameter x, in our example 0, in this formula to have the corresponding y.

The following C# method does this for us.

1 2 3 4 |
public static double StraightLineEquation(double x1, double y1, double x2, double y2, double x) { return (y2 - y1) / (x2 - x1) * (x - x1) + y1; } |

Please don’t forget that if you’re using a strong type languages like C#, do all the calculations on double variables, otherwise you’ll fall into a casting trap like this:

1 2 3 4 |
int i = 3; int j = 5; double result = i / j; // result will contain 0.0, because i and j are both int, and the math operation result will be an int value of 0 |

This problem doesn’t exist in languages like JavaScript that store all numbers in a decimal format. Now for our problem, we should call this method with these 5 parameters:

1 2 |
double y = StraightLineEquation(-100, 255, 100, 0, 0); // y will contain 127.5 |

1 |

1 |
<span style="font-family: Tahoma;">That’s it! Now if you need, you can convert the double value to int data type explicitly. </span> |

1 |
<span style="font-family: Tahoma;">Thanks for reading this article, please leave your comments and feedbacks down here.</span> |