Mapping a range of values to another

前端 未结 6 2212
谎友^
谎友^ 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:04

    Using scipy.interpolate.interp1d

    You can also use scipy.interpolate package to do such conversions (if you don't mind dependency on SciPy):

    >>> from scipy.interpolate import interp1d
    >>> m = interp1d([1,512],[5,10])
    >>> m(256)
    array(7.4951076320939336)
    

    or to convert it back to normal float from 0-rank scipy array:

    >>> float(m(256))
    7.4951076320939336
    

    You can do also multiple conversions in one command easily:

    >>> m([100,200,300])
    array([ 5.96868885,  6.94716243,  7.92563601])
    

    As a bonus, you can do non-uniform mappings from one range to another, for intance if you want to map [1,128] to [1,10], [128,256] to [10,90] and [256,512] to [90,100] you can do it like this:

    >>> m = interp1d([1,128,256,512],[1,10,90,100])
    >>> float(m(400))
    95.625
    

    interp1d creates piecewise linear interpolation objects (which are callable just like functions).

    Using numpy.interp

    As noted by ~unutbu, numpy.interp is also an option (with less dependencies):

    >>> from numpy import interp
    >>> interp(256,[1,512],[5,10])
    7.4951076320939336
    

提交回复
热议问题