映射值的范围,以另一 [英] Mapping a range of values to another
问题描述
我要寻找关于如何在Python转换一个量程值到另一个想法。我工作的硬件项目和正在读来自传感器的数据,可以返回一个值的范围,我然后使用该数据来驱动需要不同范围的值的驱动器。
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.
举例来说可以说,该传感器的范围为1〜512返回值,执行机构是由价值驱动的取值范围为5至10。我想,我可以传递一个值和两个范围,并得到一个功能背映射到所述第二范围的值。如果这样的功能被命名为翻译
它可以像这样使用:
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)
在这个例子中,我期望的输出 actuator_value
是 7.5
,因为如Sensor_value
是在可能的输入范围的中间
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.
推荐答案
一个解决办法是:
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.
这篇关于映射值的范围,以另一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!