Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number range to another range, maintaining ratio

Tags:

python

math

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

like image 946
SpliFF Avatar asked May 30 '09 05:05

SpliFF


People also ask

How to change range to another range?

Click anywhere in the table and then go to Table Tools > Design on the Ribbon. In the Tools group, click Convert to Range. Right-click the table, then in the shortcut menu, click Table > Convert to Range. Note: Table features are no longer available after you convert the table back to a range.

What function is used to convert the values of one range of numbers to another?

To convert a number range to another range, maintaining the ratio the simple way would be use linear conversion.


1 Answers

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

Or a little more readable:

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

like image 118
jerryjvl Avatar answered Sep 20 '22 17:09

jerryjvl