adafruit_simplemath

Math utility functions

  • Author(s): Dan Halbert, James Carr

Implementation Notes

Software and Dependencies:

adafruit_simplemath.constrain(x: float, out_min: float, out_max: float)float

Constrains x to be within the inclusive range [out_min, out_max]. Sometimes called clip or clamp in other libraries. out_min should be less than or equal to out_max. If x is less than out_min, return out_min. If x is greater than out_max, return out_max. Otherwise just return x. If max_value is less than min_value, they will be swapped.

Parameters
  • x (float) – Value to constrain

  • out_min (float) – Lower bound of output range.

  • out_max (float) – Upper bound of output range.

Returns

Returns value constrained to given range.

Return type

float

adafruit_simplemath.map_range(x: float, in_min: float, in_max: float, out_min: float, out_max: float)float

Maps a number from one range to another. Somewhat similar to the Arduino map() function, but returns a floating point result, and constrains the output value to be between out_min and out_max. If in_min is greater than in_max or out_min is greater than out_max, the corresponding range is reversed, allowing, for example, mapping a range of 0-10 to 50-0.

See also map_unconstrained_range()

from adafruit_simplemath import map_range

percent = 23
screen_width = 320  # or board.DISPLAY.width
x = map_range(percent, 0, 100, 0, screen_width - 1)
print("X position", percent, "% from the left of screen is", x)
Parameters
  • x (float) – Value to convert

  • in_min (float) – Start value of input range.

  • in_max (float) – End value of input range.

  • out_min (float) – Start value of output range.

  • out_max (float) – End value of output range.

Returns

Returns value mapped to new range.

Return type

float

adafruit_simplemath.map_unconstrained_range(x: float, in_min: float, in_max: float, out_min: float, out_max: float)float

Maps a number from one range to another. Somewhat similar to the Arduino map() function, but returns a floating point result, and does not constrain the output value to be between out_min and out_max. If in_min is greater than in_max or out_min is greater than out_max, the corresponding range is reversed, allowing, for example, mapping a range of 0-10 to 50-0.

See also map_range()

from adafruit_simplemath import map_unconstrained_range

celsius = -20
fahrenheit = map_unconstrained_range(celsius, 0, 100, 32, 212)
print(celsius, "degress Celsius =", fahrenheit, "degrees Fahrenheit")
Parameters
  • x (float) – Value to convert

  • in_min (float) – Start value of input range.

  • in_max (float) – End value of input range.

  • out_min (float) – Start value of output range.

  • out_max (float) – End value of output range.

Returns

Returns value mapped to new range.

Return type

float