Mapping a range of values to another

前端 未结 6 2222
谎友^
谎友^ 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 03:12

    def maprange(a, b, s):
        (a1, a2), (b1, b2) = a, b
        return  b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
    
    
    a = [from_lower, from_upper]
    b = [to_lower, to_upper]
    

    found at https://rosettacode.org/wiki/Map_range#Python_

    • does not clamp the transformed values to the ranges a or b (it extrapolates)
    • also works when from_lower > from_upper or to_lower > to_upper

提交回复
热议问题