# `mathutils` - Mathematical functions¶

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

class `boltons.mathutils.``Bits`(val=0, len_=None)[source]

An immutable bit-string or bit-array object. Provides list-like access to bits as bools, as well as bitwise masking and shifting operators. Bits also make it easy to convert between many different useful representations:

• bytes – good for serializing raw binary data
• int – good for incrementing (e.g. to try all possible values)
• list of bools – good for iterating over or treating as flags
• hex/bin string – good for human readability
`as_bin`()[source]
`as_bytes`()[source]
`as_hex`()[source]
`as_int`()[source]
`as_list`()[source]
classmethod `from_bin`(bin)[source]
classmethod `from_bytes`(bytes_)[source]
classmethod `from_hex`(hex)[source]
classmethod `from_int`(int_, len_=None)[source]
classmethod `from_list`(list_)[source]
`len`
`val`

## 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.