# Convert a number range to another range, maintaining ratio

### Question

I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.

I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).

1
229
5/30/2009 5:48:22 AM

``````NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
``````

``````OldRange = (OldMax - OldMin)
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
``````

Or if you want to protect for the case where the old range is 0 (OldMin = OldMax):

``````OldRange = (OldMax - OldMin)
if (OldRange == 0)
NewValue = NewMin
else
{
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
}
``````

Note that in this case we're forced to pick one of the possible new range values arbitrarily. Depending on context, sensible choices could be: `NewMin` (see sample), `NewMax` or `(NewMin + NewMax) / 2`

457
5/11/2014 5:14:37 AM

That's a simple linear conversion.

``````new_value = ( (old_value - old_min) / (old_max - old_min) ) * (new_max - new_min) + new_min
``````

So converting 10000 on the scale of -16000 to 16000 to a new scale of 0 to 100 yields:

``````old_value = 10000
old_min = -16000
old_max = 16000
new_min = 0
new_max = 100

new_value = ( ( 10000 - -16000 ) / (16000 - -16000) ) * (100 - 0) + 0
= 81.25
``````