我必须将数字缩放到0到9之间,如何在flutter应用程序中做到这一点?
我的数据是从0.000001到>500,
我需要它从0到9
最简单的方法是首先将数据标准化为0-1范围:
final normalized = (data - min) / (max - min);
然后乘以你的新最大值:
final converted = normalized * 9;
对于最小-最大归一化:
最小值=0.000001Max=n(需要定义上限以替换>500(
新值=(值*9(/(最大-最小(
我在找这个&创建了这个方法,我在范围内按比例缩放一个数字
/// Scale value between two different range
double scaler(
double value,
double start1,
double stop1,
double start2,
double stop2,
) {
final result =
((value - start1) / (stop1 - start1)) * (stop2 - start2) + start2;
return result;
}
以及测试用例
void main() {
group('scaler', () {
test("value 1.5, scale (0,3) to (0,10), should return 5 ", () {
final matcher = scaler(1.5, 0, 3, 0, 10);
expect(5, matcher);
});
test("value 1.5, scale (0,3) to (-4.2, 6.7), should return 1.25 ", () {
final matcher = scaler(1.5, 0, 3, -4.2, 6.7);
expect(1.25, matcher);
});
});
}