Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds remap function to converters.py #8

Merged
merged 1 commit into from Mar 3, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
53 changes: 53 additions & 0 deletions python_utils/converters.py
Expand Up @@ -234,3 +234,56 @@ def scale_1024(x, n_prefixes):
scaled = float(x) / (2 ** (10 * power))
return scaled, power


def remap(value, old_min, old_max, new_min, new_max):
"""
remap a value from one range into another.

>>> remap(500, 0, 1000, 0, 100)
50
>>> remap(250.0, 0.0, 1000.0, 0.0, 100.0)
25.0
>>> remap(-75, -100, 0, -1000, 0)
-750
>>> remap(33, 0, 100, -500, 500)
-170

This is a great use case example. Take an AVR that has dB values the minimum being -80dB and the maximum
being 10dB and you want to convert volume percent to the equilivint in that dB range

>>> remap(46.0, 0.0, 100.0, -80.0, 10.0)
-38.6

:param value: value to be converted
:type value: int, float

:param old_min: minimum of the range for the value that has been passed
:type old_min: int, float

:param old_max: maximum of the range for the value that has been passed
:type old_max: int, float

:param new_min: the minimum of the new range
:type new_min: int, float

:param new_max: the maximum of the new range
:type new_max: int, float

:return: value that has been re ranged, if the value is an int floor division is used so the
returned value will always be rounded down to the closest whole number.
:rtype: int, float
"""
old_range = old_max - old_min
new_range = new_max - new_min
if new_range == 0:
return 0

if old_range == 0:
new_value = new_min
else:
if isinstance(value, int):
new_value = (((value - old_min) * new_range) // old_range) + new_min
else:
new_value = (((value - old_min) * new_range) / old_range) + new_min

return new_value