mathutils - Mathematical functions

This module provides useful math functions on top of Python’s built-in math module.

Alternative Rounding Functions

boltons.mathutils.clamp(x, lower=-inf, upper=inf)[source]

Limit a value to a given range.

Parameters:
  • x (int or float) – Number to be clamped.
  • lower (int or float) – Minimum value for x.
  • upper (int or float) – Maximum value for x.

The returned value is guaranteed to be between lower and upper. Integers, floats, and other comparable types can be mixed.

>>> clamp(1.0, 0, 5)
1.0
>>> clamp(-1.0, 0, 5)
0
>>> clamp(101.0, 0, 5)
5
>>> clamp(123, upper=5)
5

Similar to numpy’s clip function.

boltons.mathutils.ceil(x, options=None)[source]

Return the ceiling of x. If options is set, return the smallest integer or float from options that is greater than or equal to x.

Parameters:
  • x (int or float) – Number to be tested.
  • options (iterable) – Optional iterable of arbitrary numbers (ints or floats).
>>> VALID_CABLE_CSA = [1.5, 2.5, 4, 6, 10, 25, 35, 50]
>>> ceil(3.5, options=VALID_CABLE_CSA)
4
>>> ceil(4, options=VALID_CABLE_CSA)
4
boltons.mathutils.floor(x, options=None)[source]

Return the floor of x. If options is set, return the largest integer or float from options that is less than or equal to x.

Parameters:
  • x (int or float) – Number to be tested.
  • options (iterable) – Optional iterable of arbitrary numbers (ints or floats).
>>> VALID_CABLE_CSA = [1.5, 2.5, 4, 6, 10, 25, 35, 50]
>>> floor(3.5, options=VALID_CABLE_CSA)
2.5
>>> floor(2.5, options=VALID_CABLE_CSA)
2.5

Note: ceil() and floor() functions are based on this example using from the bisect module in the standard library. Refer to this StackOverflow Answer for further information regarding the performance impact of this approach.