如何按比例缩小具有已知最小值和最大值的数字 [英] How to scale down a range of numbers with a known min and max value

查看:197
本文介绍了如何按比例缩小具有已知最小值和最大值的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图弄清楚如何取一个数字范围并将值缩小以适合一个范围.想要这样做的原因是我试图在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放入函数中并得出0可以通过

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

这就是我们想要的.因此,我们需要进行平移和缩放.现在,如果要获取ab的任意值,则需要更复杂一些的东西:

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

您可以验证将min放入x现在可以得到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)是新范围的大小和原始范围的大小之间的比例因子.因此,实际上我们首先是将x转换为-min,将其缩放为正确的因子,然后再将其转换回新的最小值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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆