Numbers
One-stop shop for all things numbers
The numbers
module is used to manipulate numbers, typically by rounding and simplifying them, in utilities-industry-standard ways.
Usage
from xocto.numbers import quantise
>>> quantise(256, 5)
255
See xocto.numbers for more details, including examples and in depth technical details.
API Reference
- xocto.numbers.clip_to_range(val: Comparable[T], *, minval: Comparable[T], maxval: Comparable[T]) Comparable[T] [source]
Clip the value to the min and max values given.
Values to be compared must be of the same type.
- Example usage:
>>> clip_to_range(10, minval=20, maxval=25) 20 >>> clip_to_range(date(2020, 1, 4), minval=date(2020, 1, 1), maxval=date(2020, 1, 3)) date(2020, 1, 3) >>> clip_to_range(1.5, minval=1.0, maxval=2.0) 1.5
- xocto.numbers.quantise(number: int | float | str, base: int, rounding: str = 'ROUND_HALF_EVEN') int [source]
Round a number to an arbitrary integer base. For example: >>> quantise(256, 5) 255
Note that numbers equal to half of the rounding amount will always round down. So: >>> quantise(15, 30) 0
- xocto.numbers.random_int(length: int) int [source]
Return a pseudo-random integer based on the provided length.
>>> random_int(3) 114
- xocto.numbers.remove_exponent(d: Decimal) Decimal [source]
Util function for removing the exponent and trailing zeroes of a decimal.
From https://docs.python.org/3/library/decimal.html#decimal-faq
- xocto.numbers.round_decimal_places(value: Decimal, places: int = 1, rounding: str = 'ROUND_HALF_UP') Decimal [source]
Round a decimal to a given number of decimal places using a given rounding method.
By default, we use half-up rounding so that parts from half way between the given rounding precision will be rounded up towards the greater number.
This differs from the default rounding since Python 3.0 which is also used elsewhere in Kraken (which use “banker’s”/half-even rounding, which is considered by IEEE 754 to be the recommended default for decimal).
>>> round_decimal_places(12.35, 1) 12.4
>>> round_decimal_places(-12.35, 1) -12.3 #-12.3 is bigger than -12.4
- xocto.numbers.round_to_integer(value: Decimal, rounding: str = 'ROUND_HALF_UP') int [source]
Round a decimal to the nearest integer, using a given rounding method.
By default, we use half-up rounding.
This differs from the default rounding since Python 3.0 which is also used elsewhere in Kraken (which use “banker’s”/half-even rounding, which is considered by IEEE 754 to be the recommended default for decimal).
- xocto.numbers.truncate_decimal_places(value: Decimal, places: int = 1) float [source]
Truncate a float (i.e round towards zero) to a given number of decimal places.
NB: Takes a decimal but returns a float!
>>> truncate_decimal_places(12.364, 1) 12.3
>>> round_decimal_places(-12.364, 1) -12.3 # -12.3 is bigger than -12.4
>>> round_decimal_places(12.364, 0) 12.0 # rounding to 0 returns float with no decmial part