实际上有些情况下,上面的答案会打破。 如错误输入值,错误输入范围,负输入/输出范围。
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