tags:

views:

1282

answers:

2

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

+5  A: 

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
cletus
This is wrong. You need to subtract Old Min from Old Value before the divide.
SPWorley
Um, I am ......
cletus
+6  A: 

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

jerryjvl
does oldMax have to be 16000 or can it be the highest value in the old point set (say, 15034.00, for example) is the distinction important?
SpliFF
You can make it anything you want... keep in mind that you may get strange results if one of the ranges is very small relative to the other one (not exactly sure, but if there's more than a 1000000 factor difference between the size of the ranges, make sure that it actually behaves like you expect... or learn about floating point inaccuracy)
jerryjvl