将一系列值映射到另一个值 [英] Mapping a range of values to another

查看:33
本文介绍了将一系列值映射到另一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关如何在 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 范围内的值驱动.我想要一个函数,我可以传递一个值和两个范围并得到返回映射到第二个范围的值.如果这样的函数被命名为 translate,它可以像这样使用:

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_value7.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆