實際上有些情況下,上面的答案會打破。 如錯誤輸入值,錯誤輸入範圍,負輸入/輸出範圍。
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 cases
print remap(25.0, 0.0, 100.0, 1.0, -1.0), "==", 0.5
print remap(25.0, 100.0, -100.0, -1.0, 1.0), "==", -0.25
print remap(-125.0, -100.0, -200.0, 1.0, -1.0), "==", 0.5
print remap(-125.0, -200.0, -100.0, -1.0, 1.0), "==", 0.5
#even when value is out of bound
print remap(-20.0, 0.0, 100.0, 0.0, 1.0), "==", -0.2
謝謝兩位,我得到安寧g克萊圖斯的答案,因爲他首先得到了答案,還有一個給傑裏+1的答案,以回答我的後續問題。 – SpliFF 2009-05-30 07:35:21
實際抱歉cletus,我把它交給傑瑞,因爲他是新的,需要點。 – SpliFF 2009-05-30 07:36:55
嘿,這是年齡歧視! heheh,j/k,不用擔心。 :) – cletus 2009-05-30 07:52:21