How to scale down a range of numbers with a known min and max value


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?


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

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].

Putting min into a function and getting out 0 could be accomplished with

f(x) = x - min   ===>   f(min) = min - min = 0

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

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

You can verify that putting in min for x now gives a, and putting in max gives b.

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.

Answered By – irritate

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.