Map A Value Between Scales

14th August 2020

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

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

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.

  1. /**
  2.  * Map a value between scales.
  3.  *
  4.  * @param int|float|double $value
  5.  * The value to map.
  6.  * @param int|float|double $valueRangeStart
  7.  * The value range start.
  8.  * @param int|float|double $valueRangeEnd
  9.  * The value range end.
  10.  * @param int|float|double $newRangeStart
  11.  * The new range start.
  12.  * @param int|float|double $newRangeEnd
  13.  * The new range end.
  14.  */
  15. function map($value, $valueRangeStart, $valueRangeEnd, $newRangeStart, $newRangeEnd) {
  16. return $newRangeStart + ($newRangeEnd - $newRangeStart) * (($value - $valueRangeStart) / ($valueRangeEnd - $valueRangeStart));
  17. }

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

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

This prints out the following values.

  1. 0
  2. 10
  3. 20
  4. 30
  5. 40
  6. 50
  7. 60
  8. 70
  9. 80
  10. 90
  11. 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.