Skip to content

Commit 4902915

Browse files
committed
Gracefully handle in_min == in_max: if input is lower or higher, return out_min or out_max, if input == in_min == in_max, return 50% of the output range; oh, and don't crash
1 parent ecbd27a commit 4902915

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

simpleio.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,16 @@ def map_range(x, in_min, in_max, out_min, out_max):
238238
:return: Returns value mapped to new range
239239
:rtype: float
240240
"""
241-
mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min
241+
in_range = in_max - in_min
242+
in_delta = x - in_min
243+
if in_range != 0:
244+
mapped = in_delta / in_range
245+
elif in_delta != 0:
246+
mapped = in_delta
247+
else:
248+
mapped = .5
249+
mapped *= out_max - out_min
250+
mapped += out_min
242251
if out_min <= out_max:
243252
return max(min(mapped, out_max), out_min)
244253
return min(max(mapped, out_max), out_min)

0 commit comments

Comments
 (0)