将某个范围内的数字缩放到 python 中的另一个范围

Scaling a number between a certain range to that of another in python

是否有一种方法可以将假设范围 (a, b) 之间的数字缩放到假设 (p, q) 的不同范围?

在我的例子中,我有一个介于 0 到 1 之间的数字,即 (0, 1) 并且想对其进行缩放,使其位于 -1 到 1 的范围内,即 (-1, 1) .

例子-:

# 1 will remain 1 if scaled.
scale(1, (0, 1), (-1, 1)) # => Returns 1
# 0.5 will be scaled to 0.
scale(0.5, (0, 1), (-1, 1)) # => Returns 0
# 0 will be scaled to -1.
scale(0, (0, 1), (-1, 1)) # => Returns -1

我在 - 上找到了一些相关主题: Based on mathematical formula and does not mention any pythonic way of doing so and secondly I am not able to distinguish between the upper and lower limits and max(x), min(x)

试试这个:

def scale(x, srcRange, dstRange):
    return (x-srcRange[0])*(dstRange[1]-dstRange[0])/(srcRange[1]-srcRange[0])+dstRange[0]

当然,每个范围必须以(min, max)的形式给出。

在您的示例中,其中一个范围的形式为 (max, min)