views:

718

answers:

5

How do I map numbers, linearly, between a and b to go between c and d.

That is, I want numbers between 2 and 6 to map to numbers between 10 and 20... but I need the generalized case.

My brain is fried.

+5  A: 

Divide to get the ratio between the sizes of the two ranges, than subtract the starting value of your inital range, multiply by the ratio and add the starting value of your second range. In other words,

R = (20 - 10) / (6 - 2)
y = (x - 2) * R + 10

This evenly spreads the numbers from the first range in the second range.

Konrad Rudolph
+15  A: 

If your number X falls between A and B, and you would like Y to fall between C and D, you can apply the following linear transform:

Y = (X-A)/(B-A) * (D-C) + C

That should give you what you want, although your question is a little ambiguous, since you could also map the interval in the reverse direction. Just watch out for division by zero and you should be OK.

PeterAllenWebb
Thanks. Exactly what I was looking for.
Sam
Then maybe mark this answer as “accepted” by clicking on the tick mark next to it.
Konrad Rudolph
A: 

Each unit interval on the first range takes up (d-c)/(b-a) "space" on the second range.

Pseudo:

var interval = (d-c)/(b-a)
for n = 0 to (b - a)
    print c + n*interval

How you handle the rounding is up to you.

chris
A: 
int srcMin = 2, srcMax = 6;
int tgtMin = 10, tgtMax = 20;

int nb = srcMax - srcMin;
int range = tgtMax - tgtMin;
float rate = (float) range / (float) nb;

println(srcMin + " > " + tgtMin);
float stepF = tgtMin;
for (int i = 1; i < nb; i++)
{
  stepF += rate;
  println((srcMin + i) + " > " + (int) (stepF + 0.5) + " (" + stepF + ")");
}
println(srcMax + " > " + tgtMax);

With checks on divide by zero, of course.

PhiLho
A: 

As an aside, this is the same problem as the classic convert celcius to farenheit where you want to map a number range that equates 0 - 100 (C) to 32 - 212 (F).

Metro