如何缩小具有已知最小值和最大值的数字范围 [英] How to scale down a range of numbers with a known min and max value
问题描述
所以我想弄清楚如何取一个数字范围并将值缩小以适应一个范围.想要这样做的原因是我试图在 java swing jpanel 中绘制椭圆.我希望每个椭圆的高度和宽度都在 1-30 的范围内.我有一些方法可以从我的数据集中找到最小值和最大值,但直到运行时我才会有最小值和最大值.有没有简单的方法可以做到这一点?
So I am trying to figure out how to take a range of numbers and scale the values down to fit a range. The reason for wanting to do this is that I am trying to draw ellipses in a java swing jpanel. I want the height and width of each ellipse to be in a range of say 1-30. I have methods that find the minimum and maximum values from my data set, but I won't have the min and max until runtime. Is there an easy way to do this?
推荐答案
假设您想将范围 [min,max]
缩放到 [a,b]
.你正在寻找一个(连续的)函数,它满足
Let's say you want to scale a range [min,max]
to [a,b]
. You're looking for a (continuous) function that satisfies
f(min) = a
f(max) = b
在您的情况下,a
将是 1 而 b
将是 30,但让我们从更简单的事情开始并尝试映射 [min,max]
进入范围 [0,1]
.
In your case, a
would be 1 and b
would be 30, but let's start with something simpler and try to map [min,max]
into the range [0,1]
.
将 min
放入一个函数中,可以用
Putting min
into a function and getting out 0 could be accomplished with
f(x) = x - min ===> f(min) = min - min = 0
这几乎就是我们想要的.但是当我们真正想要 1 时,输入 max
会给我们 max - min
.所以我们必须缩放它:
So that's almost what we want. But putting in max
would give us max - min
when we actually want 1. So we'll have to scale it:
x - min max - min
f(x) = --------- ===> f(min) = 0; f(max) = --------- = 1
max - min max - min
这是我们想要的.所以我们需要进行平移和缩放.现在,如果我们想要获得 a
和 b
的任意值,我们需要一些更复杂的东西:
which is what we want. So we need to do a translation and a scaling. Now if instead we want to get arbitrary values of a
and b
, we need something a little more complicated:
(b-a)(x - min)
f(x) = -------------- + a
max - min
您可以验证为 x
输入 min
现在给出 a
,而输入 max
给出 <代码>b.
You can verify that putting in min
for x
now gives a
, and putting in max
gives b
.
您可能还注意到 (b-a)/(max-min)
是新范围大小与原始范围大小之间的比例因子.所以实际上我们首先通过 -min
转换 x
,将其缩放到正确的因子,然后将其转换回 a的新最小值代码>.
You might also notice that (b-a)/(max-min)
is a scaling factor between the size of the new range and the size of the original range. So really we are first translating x
by -min
, scaling it to the correct factor, and then translating it back up to the new minimum value of a
.
希望这会有所帮助.
这篇关于如何缩小具有已知最小值和最大值的数字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!