Map A Value Between Scales

A common technique when creating graphics or visual representations of data is to map a value between two scales. This is useful when working on a set of values and you need to map them to a different set of values in order to show them on a graph.

The maths involved here is essentially figuring out the relationship between the value (v) in our initial scale (x, y) and multiplying this by the maximum range of the second scale (a, b).

a + (b - a) * ((v - x) / (x - y))

Taking the value of 0.5, which is in the scale 0 to 1. Mapping this to the scale 0 to 100 means we make the following calculations.

0 + (100 − 0) × ((0.5 − 0) ÷ (1 − 0))

This results in the value of 50.

Converting this maths into a function in PHP we get the following.

/**
 * Map a value between scales.
 * 
 * @param int|float $value
 *   The value to map.
 * @param int|float $valueRangeStart
 *   The value range start.
 * @param int|float $valueRangeEnd
 *   The value range end.
 * @param int|float $newRangeStart
 *   The new range start.
 * @param int|float $newRangeEnd
 *   The new range end.
 *
 * @return int|float
 *   The new value, mapped to the new range.
 */
function map($value, $valueRangeStart, $valueRangeEnd, $newRangeStart, $newRangeEnd) {
  return $newRangeStart + ($newRangeEnd - $newRangeStart) * (($value - $valueRangeStart) / ($valueRangeEnd - $valueRangeStart));
}

We can use this quite easily to print out values of the range 0 to 1 as the range of 0 to 100.

for ($i = 0; $i < 1; $i += 0.1) {
  echo map($i, 0, 1, 0, 100) . PHP_EOL;
}

This prints out the following values.

0
10
20
30
40
50
60
70
80
90
100

We can also use this function to map a value of time to a decimal value.

echo map(30, 0, 60, 0, 100) . PHP_EOL;

This prints out the value of 50.

This function can also be used to normalise a larger value into a range of 0 to 1, which is useful when performing the maths within a neural network.

echo map(342, 0, 500, 0, 1) . PHP_EOL;

This prints out the value of 0.684.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.