我试图将一个范围的数字转换为另一个,保持比率。数学不是我的强项。
I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).
下面是一些简单的Python函数,便于复制和粘贴,包括一个扩展整个列表的函数。
def scale_number(unscaled, to_min, to_max, from_min, from_max):
return (to_max-to_min)*(unscaled-from_min)/(from_max-from_min)+to_min
def scale_list(l, to_min, to_max):
return [scale_number(i, to_min, to_max, min(l), max(l)) for i in l]
可以这样使用:
scale_list([1,3,4,5], 0, 100)
[0.0, 50.0, 75.0, 100.0]
在我的例子中,我想缩放一条对数曲线,像这样:
scale_list([math.log(i+1) for i in range(5)], 0, 50)
[0.0, 21.533827903669653, 34.130309724299266, 43.06765580733931, 50.0]
我个人使用支持泛型的helper类(Swift 3,4)。x兼容)
struct Rescale<Type : BinaryFloatingPoint> {
typealias RescaleDomain = (lowerBound: Type, upperBound: Type)
var fromDomain: RescaleDomain
var toDomain: RescaleDomain
init(from: RescaleDomain, to: RescaleDomain) {
self.fromDomain = from
self.toDomain = to
}
func interpolate(_ x: Type ) -> Type {
return self.toDomain.lowerBound * (1 - x) + self.toDomain.upperBound * x;
}
func uninterpolate(_ x: Type) -> Type {
let b = (self.fromDomain.upperBound - self.fromDomain.lowerBound) != 0 ? self.fromDomain.upperBound - self.fromDomain.lowerBound : 1 / self.fromDomain.upperBound;
return (x - self.fromDomain.lowerBound) / b
}
func rescale(_ x: Type ) -> Type {
return interpolate( uninterpolate(x) )
}
}
Ex:
let rescaler = Rescale<Float>(from: (-1, 1), to: (0, 100))
print(rescaler.rescale(0)) // OUTPUT: 50
在由PenguinTD提供的清单中,我不明白为什么范围是颠倒的,它不需要颠倒范围就能工作。线性范围转换基于线性方程Y=Xm+n,其中m和n是从给定的范围推导出来的。与其将范围称为min和max,不如将它们称为1和2。所以公式是:
Y = (((X - x1) * (y2 - y1)) / (x2 - x1)) + y1
当X=x1时Y=y1,当X=x2时Y=y2。X1, x2, y1和y2可以取任意正值或负值。在宏中定义表达式使其更有用,它可以与任何参数名称一起使用。
#define RangeConv(X, x1, x2, y1, y2) (((float)((X - x1) * (y2 - y1)) / (x2 - x1)) + y1)
在所有实参都是整数值的情况下,浮点强制转换将确保浮点除法。
根据应用程序的不同,可能不需要检查x1=x2和y1==y2的范围。
Java版本
不管你喂它什么,它都能工作!
我把所有内容都展开了,这样便于学习。当然,最后舍入是可选的。
private long remap(long p, long Amin, long Amax, long Bmin, long Bmax ) {
double deltaA = Amax - Amin;
double deltaB = Bmax - Bmin;
double scale = deltaB / deltaA;
double negA = -1 * Amin;
double offset = (negA * scale) + Bmin;
double q = (p * scale) + offset;
return Math.round(q);
}