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).
That's a simple linear conversion.
So converting 10000 on the scale of -16000 to 16000 to a new scale of 0 to 100 yields:
This example converts a songs current position into an angle range of 20 - 40.
In the listing provided by PenguinTD, I do not understand why the ranges are reversed, it works without having to reverse the ranges. Linear range conversion is based upon the linear equation
Y=Xm+n
, wherem
andn
are derived from the given ranges. Rather than refer to the ranges asmin
andmax
, it would be better to refer to them as 1 and 2. So the formula would be:Where
Y=y1
whenX=x1
, andY=y2
whenX=x2
.x1
,x2
,y1
&y2
can be given anypositive
ornegative
value. Defining the expression in a macro makes it more useful,it can then be used with any argument names.The
float
cast would ensure floating point division in the case where all the arguments areinteger
values. Depending on the application it may not be necessary to check the rangesx1=x2
andy1==y2
.There is a condition, when all of the values that you are checking are the same, where @jerryjvl's code would return NaN.
Or a little more readable:
Or if you want to protect for the case where the old range is 0 (OldMin = OldMax):
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
I used this solution in a problem I was solving in js, so I thought I would share the translation. Thanks for the explanation and solution.