Python 中的数学比率

Maths ratios in Python

我一年前写的,虽然它达到了它的目的,但我想知道是否有比我聪明得多的人可以提出提高效率的方法。

def tempcolor(mintemp=0,maxtemp=32,mincolor=44000,maxcolor=3200,ctemp=10,c=0):
    tempdiff=(mincolor-maxcolor) / (maxtemp-mintemp)
    ccolor=(ctemp-mintemp) * tempdiff
    ctouse=(mincolor-ccolor)
    #print ctouse
    return ctouse;

有一个数字范围(mintemp 到 maxtemp)。当调用 ctouse 时,我们计算比率,然后将相同的比率应用于其他数字范围(mincolor 和 maxcolor)。

我正在另一个脚本中使用它,只是想知道是否有人有任何建议可以使它更整洁。或者更准确!

谢谢

我假设您很少或从不更改 mintemp、maxtemp、mincolor、maxcolor 的给定值。

我能看到的唯一效率改进是预先计算比率 - 类似于

def make_linear_interpolator(x0, x1, y0, y1):
    """
    Return a function to convert x in (x0..x1) to y in (y0..y1)
    """
    dy_dx = (y1 - y0) / float(x1 - x0)
    def y(x):
        return y0 + (x - x0) * dy_dx
    return y

color_to_temp = make_linear_interpolator(0, 32, 44000, 3200)

color_to_temp(10)    # => 32150.0