Range Mapping in Programming

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). Just kidding

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:

Figure 1 - Straight Line with 2 points

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 interpolation problem, the rest is as easy as a few basic math operations!

Figure 2 - find Y for X

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

( 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.

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:

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:

Leave a comment please!