使用负数缩放值范围

6 math scale

如果包含负数,我如何缩放一组值以适应新范围?

例如,我有一组数字(-10,-9,1,4,10)必须缩放到范围[0 1],这样-10映射到0,10映射到1.

任意数字'x'的常规方法是:(x - from_min)*(to_max - to_min)/(from_max - from_min)+ to_min

但这不适用于负数.任何帮助表示赞赏.谢谢!!

小智 6

我相信id可以;在你的例子中

from_min = -10,
from_max = 10,
to_max = 1,
to_min = 0.
Run Code Online (Sandbox Code Playgroud)

这产生

to_max - to_min = 1,
from_max - from_min = 20;
Run Code Online (Sandbox Code Playgroud)

所以用公式

x -> (x - from_min) * (to_max - to_min) / (from_max - from_min) + to_min
   = (x - from_min) * 1 / 20 + 0
   = (x - from_min) / 20
Run Code Online (Sandbox Code Playgroud)

产量

-10 -> (-10 + 10) / 20 = 0 / 20,
-9 -> (-9 + 10) / 20 = 1 / 20,
1 -> (1 + 10) / 20 = 11 / 20,
4 -> (4 + 10) / 20 = 14 / 20,
10 -> (10 + 10) / 20 = 20 / 20,
Run Code Online (Sandbox Code Playgroud)

因此所有结果值均为非负值。此外,原始最小值-10映射到to_min = 0,原始最大值10映射到to_max =1。如果这在您的实现中不起作用,请检查是否混合了整数类型和浮点类型。