Python中的数学比率

2024-09-28 22:29:46 发布

您现在位置: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)。在

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

谢谢

威尔


Tags: def数字建议比率篇文章提高效率人能ctemp
1条回答
网友
1楼 · 发布于 2024-09-28 22:29:46

我假设你很少或者永远不会改变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

相关问题 更多 >