1.2. Python for mathematicians: first steps#

This section is not a programming course — we assume the basics of programming (at WMI UAM, from the course Programowanie). Here we collect the elements of Python that a mathematician uses most often, and those in which it is easiest to make mistakes. For each of them we ask the same question: which mathematical object does a given type or language construct correspond to, and where does this correspondence end? Python’s integers are genuine integers, but a float is not a real number, and a list comprehension, although it resembles set-builder notation, describes a finite computation.

The style of work we will practice is computational thinking. It consists of three steps:

  1. abstraction — we state the problem precisely: what is given, what is the output, and what conditions the output must satisfy;

  2. automation — we write the solution as a program;

  3. analysis — we run the program, check it on cases we know, and assess what the result is: a proof, an approximation, or merely a conjecture.

1.2.1. Python as a calculator: integers#

Integers (int) in Python have unlimited precision. The interpreter stores them as sequences of digits in a large base (in CPython it is \(2^{30}\)) and lengthens this representation as needed. Computations are therefore exact regardless of the size of the numbers, and the only limits are memory and time. The time grows with the length of the representation: adding two \(n\)-digit numbers takes about \(n\) digit operations, and schoolbook multiplication about \(n^2\) (for very large numbers, CPython switches to the faster Karatsuba algorithm). The int type thus implements the set \(\Z\) literally.

One practical caveat: in current versions of Python, converting a number to a decimal string (str, print) is limited by default to \(4300\) digits, so, e.g., str(math.factorial(2000)) raises a ValueError; the limit can be changed with the function sys.set_int_max_str_digits, and the computations themselves are not affected by it. To begin, let us compute \(2^{100}\); the result has \(31\) digits, and Python prints it in full:

2**100
1267650600228229401496703205376

The factorial \(100! = 1 \cdot 2 \cdots 100\) has more than a hundred and fifty digits, and yet Python computes it instantly and without any rounding. Let us count its digits and compute their sum:

import math
n = math.factorial(100)
len(str(n)), sum(int(c) for c in str(n))      # liczba cyfr i suma cyfr 100!
(158, 648)

The number \(100!\) has \(158\) digits, and the sum of its digits is \(648\). The second result is easy to check partially without a computer: \(9\) divides \(100!\), and every natural number is congruent modulo \(9\) to the sum of its digits, so the digit sum must be divisible by \(9\). Indeed, \(648 = 9 \cdot 72\). Such an independent check of a result is a good habit.

Python has three operators related to division. The operator / approximates the real quotient: for arguments of type int, its result is always of type float, even when the division can be carried out in the integers. The operators // and % implement division with remainder in \(\Z\): the first gives the quotient, the second the remainder.

17 / 5, 17 // 5, 17 % 5        # dzielenie zmiennopozycyjne, iloraz całkowity, reszta
(3.4, 3, 2)

More precisely: for integers \(a\) and \(b \neq 0\), Python defines

\[ a \mathbin{//} b = \left\lfloor \frac{a}{b} \right\rfloor, \qquad a \bmod b = a - b \left\lfloor \frac{a}{b} \right\rfloor , \]

where \(a \bmod b\) is the result of the % operator. Hence always \(a = (a \mathbin{//} b)\cdot b + (a \bmod b)\), and for \(b > 0\) the remainder lies in \(\{0, 1, \dots, b-1\}\) — also for negative \(a\). It is thus exactly the remainder from the theorem on division with remainder. (For \(b < 0\) the remainder has the sign of the divisor: \(b < a \bmod b \le 0\).) This convention, called floor division, agrees with the theorem on division with remainder for positive divisors, but differs from the languages C and Java, in which the integer quotient is rounded toward zero: there, \(-7\) divided by \(2\) gives the quotient \(-3\) and the remainder \(-1\). Let us check what Python returns (the function divmod gives the quotient and the remainder at once):

a, b = -7, 2
a // b, a % b, (a // b) * b + a % b == a, divmod(a, b)
(-4, 1, True, (-4, 1))

We have \(-7 = (-4) \cdot 2 + 1\): the quotient is \(\lfloor -3.5 \rfloor = -4\), and the remainder \(1\) lies in \(\{0, 1\}\), as the theorem on division with remainder requires.

Warning

In Python, exponentiation is written **. The symbol ^ denotes bitwise exclusive or (XOR): 2^10 gives 8, because \(0010_2 \oplus 1010_2 = 1000_2\). In SageMath, the preparser turns ^ into exponentiation, so the same string has a different meaning there.

2**10, 2^10
(1024, 8)

The math module contains exact number-theoretic and combinatorial functions that work on integers of any size:

  • math.gcd(a, b) and math.lcm(a, b) — the greatest common divisor and the least common multiple;

  • math.isqrt(n) — the integer square root \(\lfloor \sqrt{n} \rfloor\), computed exactly (unlike int(math.sqrt(n)), which goes through float and may give a wrong result for large \(n\));

  • math.comb(n, k) — the binomial coefficient \(\binom{n}{k} = \frac{n!}{k!\,(n-k)!}\);

  • math.factorial(n) and math.prod(ciąg) — the factorial and the product of the elements of a sequence.

math.gcd(1071, 462), math.isqrt(10**20 + 1), math.comb(52, 5)
(21, 10000000000, 2598960)

Let us read off the results. The equality \(\gcd(1071, 462) = 21\) is a classic example of the Euclidean algorithm at work; we will return to the algorithm below. Next, \(\lfloor \sqrt{10^{20}+1} \rfloor = 10^{10}\), because \((10^{10})^2 \le 10^{20}+1 < (10^{10}+1)^2\). (Here int(math.sqrt(n)) would give the same result; the difference shows up, e.g., for \(n = 10^{16} - 1\): this number rounds to the float equal to \(10^{16}\), so int(math.sqrt(n)) returns \(10^8\), although \(\lfloor\sqrt{n}\rfloor = 10^8 - 1\).) Finally, \(\binom{52}{5} = 2{,}598{,}960\) is the number of five-element subsets of a deck of \(52\) cards, that is, of all possible poker hands.

1.2.2. Floating-point numbers — a first warning#

The float type is a 64-bit IEEE 754 floating-point number (the same as double in C). Every finite number of this type has the form \(\pm m \cdot 2^{e}\), where \(m\) is an integer, \(0 \le m < 2^{53}\), and the exponent satisfies \(-1074 \le e \le 971\). This gives a precision of about \(16\) decimal digits. It follows from this form that every finite float is a fraction whose denominator is a power of two. On the other hand, a rational number \(p/q\) written in lowest terms has a finite binary expansion if and only if \(q\) is a power of two. The fractions \(\tfrac{1}{10}\), \(\tfrac{2}{10}\), and \(\tfrac{3}{10}\) do not satisfy this condition, so float does not represent them exactly — it stores the machine numbers nearest to them:

0.1 + 0.2, 0.1 + 0.2 == 0.3
(0.30000000000000004, False)

Each of the fractions \(0.1\), \(0.2\), and \(0.3\) has been replaced by the nearest machine number, and the result of the addition has been rounded once more. The sum lands on the machine number adjacent to the one we write as 0.3 — hence the final digit 4, and the comparison is false. We take this example apart bit by bit in the deep dive Part 2. Implementation: tricks and subtleties.

The built-in function round performs rounding as well. When a number lies exactly halfway between two possible values, Python chooses the one whose last digit is even (round half to even). The IEEE 754 standard uses the same rule: unlike the schoolbook rule of rounding “halves up,” it does not systematically shift the sum of many rounded values.

round(2.5), round(3.5), round(0.125, 2)    # zaokrąglanie „do parzystej” (banker's rounding)
(2, 4, 0.12)

So round(2.5) gives \(2\), and round(3.5) gives \(4\). The result of round(0.125, 2), namely \(0.12\), is also rounding to even: \(0.125 = 2^{-3}\) is a machine number, so the tie is genuine. When a number cannot be stored exactly, there is no tie at all, and the result depends on which side of the halfway point the stored value lies. For example, round(2.675, 2) gives \(2.67\), because the literal 2.675 is stored as a number about \(1.8\cdot 10^{-16}\) smaller than \(2.675\).

When we need exact computation with fractions, we use the type fractions.Fraction. It stores a rational number as a pair of integers — a numerator and a positive denominator — in lowest terms, so operations on it are exact operations in the field \(\Q\). The price is time: numerators and denominators can grow quickly.

from fractions import Fraction
Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10)
True

The Fraction constructor also accepts a number of type float and returns its exact value. This way we can see what the computer really stores when we write 0.1:

Fraction(0.1)          # dokładna wartość liczby zmiennopozycyjnej „0.1”
Fraction(3602879701896397, 36028797018963968)

The denominator \(36{,}028{,}797{,}018{,}963{,}968\) is \(2^{55}\), in line with what we said about binary expansions. The stored number is slightly larger than \(\tfrac{1}{10}\): the difference is exactly \(\tfrac{1}{5 \cdot 2^{55}} \approx 5.55 \cdot 10^{-18}\).

We will study floating-point arithmetic in detail later in the course (it is one of the course’s main topics; see also the deep dive IEEE 754: floating-point numbers from the inside). For now, remember: comparing float values with the == operator is usually a mistake. Instead, we use exact computation or the function math.isclose(a, b), which checks the condition

\[ |a - b| \le \max\bigl(r \cdot \max(|a|, |b|),\ t\bigr) \]

with a relative tolerance \(r\) (the argument rel_tol, by default \(10^{-9}\)) and an absolute tolerance \(t\) (the argument abs_tol, by default \(0\)). When comparing with zero, the relative condition is of no use, so an absolute tolerance must be given.

1.2.3. Data types and their mathematical counterparts#

Every built-in type has a natural mathematical counterpart, but the correspondence is not always exact. The int type implements \(\Z\) (within the limits of memory). The finite values of type float, on the other hand, form a finite subset of \(\Q\) — fractions whose denominators are powers of two, with bounded numerators and denominators (precisely: the numbers \(\pm m \cdot 2^{e}\) described above) — extended by \(\pm\infty\) and the value NaN (not a number). The table gives the full overview; in it, the collections (from str down) correspond to finite objects:

Python

Example

Mathematics

int

-3, 2**100

\(\Z\) (exactly)

float

0.1, 1e-9

approximations of real numbers

complex

1 + 2j

approximations of complex numbers

bool

True, False

truth values (True == 1)

str

"abc"

words over an alphabet

list

[1, 2, 2]

finite sequences

tuple

(1, 2)

tuples (pairs, triples, …)

set

{1, 2}

finite sets

dict

{1: 'a', 2: 'b'}

functions with a finite domain

The function type gives the type of a value. Let us check the types of the results of a few operations; the last expression shows how Python treats truth values:

type(7), type(7 / 1), type(1j**2), True + True
(int, float, complex, 2)

The division 7 / 1 gives a float, although the result is an integer: the type of the result depends on the operator, not on the value. The power 1j**2 is the complex number \(-1\), of type complex. Finally, True + True equals \(2\), because the type bool is a subtype of int, and True and False are simply \(1\) and \(0\).

1.2.4. List comprehensions as set-builder notation#

The mathematical notation \(\{\, n^2 : n \in \{1,\dots,10\},\ 2 \nmid n \,\}\) has an almost literal counterpart in Python — a list comprehension or a set comprehension. Note the range: range(1, 11) is the set \(\{1, 2, \dots, 10\}\), because the range range(a, b) contains \(a\) but does not contain \(b\).

[n**2 for n in range(1, 11) if n % 2 == 1]
[1, 9, 25, 49, 81]

Several for loops in one expression correspond to several bound variables, and the if condition to the conditions imposed on these variables. The set comprehension below is

\[ \{(a, b, c) : 1 \le a < b < c < 30,\ a^2 + b^2 = c^2,\ \gcd(a, b) = 1\}, \]

that is, the set of primitive Pythagorean triples with hypotenuse less than \(30\):

{(a, b, c) for c in range(1, 30) for b in range(1, c) for a in range(1, b)
 if a*a + b*b == c*c and math.gcd(a, b) == 1}           # pierwotne trójki pitagorejskie
{(3, 4, 5), (5, 12, 13), (7, 24, 25), (8, 15, 17), (20, 21, 29)}

The search is exhaustive, so these are all such triples. This agrees with a classical theorem: the primitive triples are exactly the triples \((m^2 - n^2,\ 2mn,\ m^2 + n^2)\), up to the order of the legs, for coprime \(m > n \ge 1\) of opposite parity. Five such pairs satisfy the condition \(m^2 + n^2 < 30\): \((2, 1)\), \((3, 2)\), \((4, 1)\), \((4, 3)\), and \((5, 2)\).

Quantifiers and summation-like operators also have counterparts: all (\(\forall\)), any (\(\exists\)), sum (\(\Sigma\)), math.prod (\(\Pi\)), max, min. They work on finite sequences and follow the usual conventions for the empty set: all([]) is True, any([]) is False, the empty sum is \(0\), and the empty product is \(1\). The exceptions are max and min: for an empty sequence they raise a ValueError, because the empty set has no largest or smallest element. Let us check Gauss’s formula \(1 + 2 + \dots + n = \frac{n(n+1)}{2}\) for all \(n < 1000\):

N = 1000
all(sum(range(1, n + 1)) == n * (n + 1) // 2 for n in range(N))     # ∀ n < N: 1+…+n = n(n+1)/2
True

The result True is a verification of finitely many cases (a thousand of them: \(n = 0, 1, \dots, 999\)), not a proof of a theorem about all \(n \in \N\). (Note also that the division // 2 is exact here, because the product \(n(n+1)\) is always even.) We will return to the difference between verification and proof in the section Computation, verification, proof, where we will prove the same formula formally.

1.2.5. Functions, loops, conditionals#

The Euclidean algorithm rests on two equalities: \(\gcd(a, b) = \gcd(b,\ a \bmod b)\) for \(b \neq 0\), and \(\gcd(a, 0) = |a|\). The remainders decrease in absolute value, so the algorithm always terminates. Let us write it with a step counter (we will use it again in the lab):

def nwd(a, b):
    """Zwraca (NWD(a, b), liczba kroków dzielenia z resztą)."""
    kroki = 0
    while b != 0:
        a, b = b, a % b
        kroki += 1
    return abs(a), kroki

nwd(1071, 462), nwd(89, 55)       # 89 i 55 to kolejne liczby Fibonacciego
((21, 3), (1, 9))

For the pair \((1071, 462)\) three steps suffice, while for the consecutive Fibonacci numbers \(89\) and \(55\) it takes as many as nine. This is no accident: by Lamé’s theorem (1844), consecutive Fibonacci numbers are the worst case for the Euclidean algorithm, and for \(a \ge b > 0\) the number of steps never exceeds five times the number of decimal digits of the smaller number (see exercise B4 in the problem set Lab 1: VS Code, Jupyter, and Python as a mathematician’s calculator). The assumption \(a \ge b\) matters: for \(a < b\) our function performs an extra step that merely swaps the arguments, and, e.g., nwd(8, 13) needs \(6\) steps, although \(5 \cdot 1 = 5\).

The Collatz problem. Let \(T(n) = n/2\) for even \(n\) and \(T(n) = 3n + 1\) otherwise. The Collatz conjecture (1937) states that for every \(n \ge 1\) the sequence \(n, T(n), T(T(n)), \dots\) eventually reaches \(1\). It has been verified by computer for an enormous range of numbers, but nobody knows a proof. Even so, the process itself is easy to program:

def collatz(n):
    ciag = [n]
    while n != 1:
        n = n // 2 if n % 2 == 0 else 3 * n + 1
        ciag.append(n)
    return ciag

c = collatz(27)
len(c) - 1, max(c)          # liczba kroków i największa wartość dla n = 27
(111, 9232)

For \(n = 27\) it takes \(111\) steps, and along the way the sequence climbs as high as \(9232\). Such irregular behavior, already for a small starting number, shows well why the conjecture is hard.

Recursion and memoization. The Fibonacci numbers satisfy \(F_0 = 0\), \(F_1 = 1\), and \(F_n = F_{n-1} + F_{n-2}\) for \(n \ge 2\). The definition transcribed directly as a recursive function is correct, but useless for large \(n\): computing \(F_n\) requires \(2F_{n+1} - 1\) function calls (an easy proof by induction), and \(F_n \approx \varphi^n / \sqrt{5}\), where \(\varphi = \frac{1+\sqrt{5}}{2}\), grows exponentially. The decorator functools.lru_cache remembers the values already computed, so each of the numbers \(F_0, F_1, \dots, F_n\) is computed only once:

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

fib(100)
354224848179261915075

With memoization, the result appears instantly. Without @lru_cache, the same definition would make \(2F_{101} - 1 > 10^{21}\) calls, that is, in practice it would never finish — a good illustration that a correct program need not be a useful one.

1.2.6. Modules we will use#

Python’s standard library and a few external packages cover almost everything we need in this course:

Module

What for

math, fractions, decimal

mathematical functions, exact fractions, decimal arithmetic

itertools

combinatorics: product, combinations, permutations

random

pseudorandom numbers (reproducible once the seed is fixed: random.seed(0))

numpy

fast computations on arrays of numbers (vectors, matrices)

matplotlib

plots

sympy

symbolic computation

mpmath

arbitrary-precision arithmetic and interval arithmetic

Finally, let us plot Collatz trajectories for several starting values. On the vertical axis we use a logarithmic scale, because the values vary over several orders of magnitude.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7, 3.2))
for start in (27, 31, 41, 47):
    ax.plot(collatz(start), lw=1.2, label=f"n = {start}")
ax.set_yscale("log")
ax.set_xlabel("krok")
ax.set_ylabel("wartość")
ax.legend()
ax.set_title("Trajektorie Collatza")
plt.show()
../_images/970a78b96e540919f5fe595d8280f661a20a83f55da161a09e015658cc86bed9.png

The curves look like shifted copies of a single trajectory — and that is exactly what they are. The sequence for \(27\) passes through the other three starting values (\(27 \to 82 \to 41 \to 124 \to 62 \to 31 \to 94 \to 47 \to \dots\)), so their trajectories are final segments of the trajectory of \(27\) and reach the same maximum, \(9232\).

1.2.7. Good habits#

  • Write small functions with readable names and a short description (a docstring).

  • Test on cases you know, e.g., assert nwd(12, 18)[0] == 6.

  • Fix the seed of the random number generator (random.seed(0)) so that results are reproducible.

  • Separate the computation from the conclusion: the output of a program is a piece of data, not a theorem. Before you interpret it, ask whether it checks finitely many cases, whether it is an approximation, or whether it follows from a proof.