31 May 2012

Math - Scaling a value

Sometimes you have this thing where you have two ranges, and you need to scale a value from the one to the other; e.g.:
Range 1: 0.....x.....100   x=50
Range 2: 0.....y.....500   y=?
Thus:
100 > 500
 50 >   ?
  x >   y

C# code

Thus, I want to know the value of y. I wrote this extension to get it:
internal static double Scale(this double value, double maxValue, double maxScale) {
  if (maxValue == 0 || maxScale == 0)
    return 0;
  else if (maxValue == maxScale)
    return value;
  else
    return value / (maxValue / maxScale);
}

result = 50.Scale(100, 500); //Result will be 250

Try it


if (max. value)equals (max. scale)
then (value)is (result)
...

See also

Interpolating a value

No comments:

Post a Comment