Mapping a range of values to another

前端 未结 6 2226
谎友^
谎友^ 2020-11-28 02:39

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

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 02:55

    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.

提交回复
热议问题