Math functions

Articles

https://martinheinz.dev

Meanwhile in the math module, bunch of miscellaneous functions were added or improved. Starting with the improvement to one existing function:

math.gcd

import math

# Greatest common divisor
math.gcd(80, 64, 152)
# 8

Previously gcd function which calculates the Greatest Common Divisor could only be applied to 2 numbers, forcing programmers to do something like this math.gcd(80, math.gcd(64, 152)), when working with more numbers.

Starting with Python 3.9, we can apply it to any number of values.

math.lcm

math.lcm calculates Least Common Multiple of its arguments. Same as with GCD, it allows variable number of arguments.

First new addition to math module is math.lcm function:

# Least common multiple
math.lcm(4, 8, 5)
# 40

math.nextafter

The 2 remaining new functions are very much related.

These are math.nextafter and math.ulp :

# Next float after 4 going towards 5
math.nextafter(4, 5)
4.000000000000001
# Next float after 9 going towards 0
math.nextafter(9, 0)
8.999999999999998

The math.nextafter(x, y) function is pretty straightforward - it’s next float after x going towards y while taking into consideration floating-point number precision.

math.ulp (Unit in the Last Place)

The math.ulp on the other hand might look little weird…

ULP stands for “Unit in the Last Place” and it’s used as a measure of accuracy in numeric calculations. Shortest explanation is using an example:

Let’s imagine that we don’t have 64 bit computer. Instead, all we have is just 3 digits. With these 3 digits we can represent number like 3.14, but not 3.141.

With 3.14, the nearest larger number that we can represent is 3.15,

These 2 numbers differ by 1 ULP (Units at the last place), which is 0.1.

So, what the math.ulp returns is equivalent of this example, but with actual precision of your computer.

# Unit in the Last Place
math.ulp(1000000000000000)
0.125

math.ulp(3.14159265)
4.440892098500626e-16

For proper example and explanation see nice writeup at https://matthew-brett.github.io/teaching/floating_error.html .