mpu.math

Mathematical functions which are not adequately covered by standard libraries.

Standard libraries are:

mpu.math.argmax(iterable)[source]

Find the first index of the biggest value in the iterable.

Parameters

iterable (iterable) –

Returns

argmax

Return type

int

Examples

>>> argmax([0, 0, 0])
0
>>> argmax([1, 0, 0])
0
>>> argmax([0, 1, 0])
1
>>> argmax([])
mpu.math.factorize(number)[source]

Get the prime factors of an integer except for 1.

Parameters

number (int) –

Returns

primes

Return type

iterable

Examples

>>> factorize(-17)
[-1, 17]
>>> factorize(8)
[2, 2, 2]
>>> factorize(3**25)
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
>>> factorize(1)
[1]
mpu.math.gcd(a: int, b: int) → int[source]

Calculate the greatest common divisor.

Currently, this uses the Euclidean algorithm.

Parameters
  • a (int) – Non-zero

  • b (int) –

Returns

greatest_common_divisor

Return type

int

Examples

>>> gcd(1, 7)
1
>>> gcd(-1, -1)
1
>>> gcd(1337, 42)
7
>>> gcd(-1337, -42)
7
>>> gcd(120, 364)
4
>>> gcd(273, 1870)
1
mpu.math.generate_primes()[source]

Generate an infinite sequence of prime numbers.

The algorithm was originally written by David Eppstein, UC Irvine. See: http://code.activestate.com/recipes/117119/

Examples

>>> g = generate_primes()
>>> next(g)
2
>>> next(g)
3
>>> next(g)
5
mpu.math.is_prime(number)[source]

Check if a number is prime.

Parameters

number (int) –

Returns

is_prime_number

Return type

bool

Examples

>>> is_prime(-17)
False
>>> is_prime(17)
True
>>> is_prime(47055833459)
True
mpu.math.product(iterable, start=1)[source]

Calculate the product of the iterables.

Parameters
  • iterable (iterable) – List, tuple or similar which contains numbers

  • start (number, optional (default: 1)) –

Returns

product

Return type

number

Examples

>>> product([1, 2, 3, 4, 5])
120
>>> product([])
1
mpu.math.round_down(x, decimal_places)[source]

Round a float down to decimal_places.

Parameters
  • x (float) –

  • decimal_places (int) –

Returns

rounded_float

Return type

float

Examples

>>> round_down(1.23456, 3)
1.234
>>> round_down(1.23456, 2)
1.23
mpu.math.round_up(x, decimal_places)[source]

Round a float up to decimal_places.

Parameters
  • x (float) –

  • decimal_places (int) –

Returns

rounded_float

Return type

float

Examples

>>> round_up(1.2344, 3)
1.235
>>> round_up(1.234, 3)
1.234
>>> round_up(1.23456, 3)
1.235
>>> round_up(1.23456, 2)
1.24