Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a range of values to another

I am looking for ideas on how to translate one range values to another in Python. I am working on hardware project and am reading data from a sensor that can return a range of values, I am then using that data to drive an actuator that requires a different range of values.

For example lets say that the sensor returns values in the range 1 to 512, and the actuator is driven by values in the range 5 to 10. I would like a function that I can pass a value and the two ranges and get back the value mapped to the second range. If such a function was named translate it could be used like this:

sensor_value = 256 actuator_value = translate(sensor_value, 1, 512, 5, 10) 

In this example I would expect the output actuator_value to be 7.5 since the sensor_value is in the middle of the possible input range.

like image 447
Tendayi Mawushe Avatar asked Dec 28 '09 12:12

Tendayi Mawushe


People also ask

How do you map a value to another value?

If you need to map or translate inputs to arbitrary values, you can use the VLOOKUP function. Since there is no way to derive the output (i.e. it's arbitrary), we need to do some kind of lookup. The VLOOKUP function provides an easy way to do this.

How do you find the range of values?

The range is the difference between the smallest and highest numbers in a list or set. To find the range, first put all the numbers in order. Then subtract (take away) the lowest number from the highest. The answer gives you the range of the list.

What is map() in Arduino?

The Arduino map() function. The map() function makes it easy to convert numbers from one range to another. Here's a simple example of its usage. The map() function makes it easy to convert a value from one range into a proportional value of another range.

What is the limitation of the map() function?

The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated, and are not rounded or averaged.


1 Answers

One solution would be:

def translate(value, leftMin, leftMax, rightMin, rightMax):     # Figure out how 'wide' each range is     leftSpan = leftMax - leftMin     rightSpan = rightMax - rightMin      # Convert the left range into a 0-1 range (float)     valueScaled = float(value - leftMin) / float(leftSpan)      # Convert the 0-1 range into a value in the right range.     return rightMin + (valueScaled * rightSpan) 

You could possibly use algebra to make it more efficient, at the expense of readability.

like image 114
Adam Luchjenbroers Avatar answered Sep 20 '22 01:09

Adam Luchjenbroers