Convert a number range to another range, maintaining ratio Convert a number range to another range, maintaining ratio python python

Convert a number range to another range, maintaining ratio


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 = NewMinelse{    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


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 = 10000old_min = -16000old_max = 16000new_min = 0new_max = 100new_value = ( ( 10000 - -16000 ) / (16000 - -16000) ) * (100 - 0) + 0          = 81.25


Actually there are some cases that above answers would break.Such as wrongly input value, wrongly input range, negative input/output ranges.

def remap( x, oMin, oMax, nMin, nMax ):    #range check    if oMin == oMax:        print "Warning: Zero input range"        return None    if nMin == nMax:        print "Warning: Zero output range"        return None    #check reversed input range    reverseInput = False    oldMin = min( oMin, oMax )    oldMax = max( oMin, oMax )    if not oldMin == oMin:        reverseInput = True    #check reversed output range    reverseOutput = False       newMin = min( nMin, nMax )    newMax = max( nMin, nMax )    if not newMin == nMin :        reverseOutput = True    portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin)    if reverseInput:        portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin)    result = portion + newMin    if reverseOutput:        result = newMax - portion    return result#test casesprint remap( 25.0, 0.0, 100.0, 1.0, -1.0 ), "==", 0.5print remap( 25.0, 100.0, -100.0, -1.0, 1.0 ), "==", -0.25print remap( -125.0, -100.0, -200.0, 1.0, -1.0 ), "==", 0.5print remap( -125.0, -200.0, -100.0, -1.0, 1.0 ), "==", 0.5#even when value is out of boundprint remap( -20.0, 0.0, 100.0, 0.0, 1.0 ), "==", -0.2


matomo