HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Map a number to a different range

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
maprangepythonnumberdifferent

Problem

When working with numbers, you may need to map a number from one range to another range. This is particularly useful when you need to normalize values or convert between different units of measurement.
Luckily, all you really need is to use a simple mathematical formula to map a number from one range to another range.
You need to know the minimum and maximum values of both ranges, as well as the number you want to map. Then, calculate the difference from the minimum value of the input range, divide it by the difference between the maximum and minimum values of the input range, and multiply it by the difference between the maximum and minimum values of the output range.
Finally, add the minimum value of the output range to get the mapped value. In order to make sure the result is a floating-point number, you can use the float() function.

Solution

def num_to_range(num, inMin, inMax, outMin, outMax):
  return outMin + (float(num - inMin) / float(inMax - inMin) * (outMax
                  - outMin))

num_to_range(5, 0, 10, 0, 100) # 50.0


You need to know the minimum and maximum values of both ranges, as well as the number you want to map. Then, calculate the difference from the minimum value of the input range, divide it by the difference between the maximum and minimum values of the input range, and multiply it by the difference between the maximum and minimum values of the output range.
Finally, add the minimum value of the output range to get the mapped value. In order to make sure the result is a floating-point number, you can use the float() function.

Code Snippets

def num_to_range(num, inMin, inMax, outMin, outMax):
  return outMin + (float(num - inMin) / float(inMax - inMin) * (outMax
                  - outMin))

num_to_range(5, 0, 10, 0, 100) # 50.0

Context

From 30-seconds-of-code: num-to-range

Revisions (0)

No revisions yet.