Komputerowe rozwiązywanie problemów matematycznych · lecture

Lecture 1:
How does a computer do mathematics?

Working environment · computer algebra systems · numerics, symbolic computation and formal proof

numericssymbolic computation (CAS)formal proof

Dr. Bartosz Naskręcki · Wydział Matematyki i Informatyki UAM · 06-S1MA03-P16780
winter semester 2026/27 · course taught in Polish — dates and rooms: Harmonogram (in Polish)

Lecture outline

0
Organization
schedule, assessment, materials
5 min
I
Three worlds of computation
numerics · symbolic computation · proof
7 min
II
Working environment
VS Code, Python, SymPy, SageMath
18 min
III–VI
Continued
how a CAS works → Lecture 2 · the sum 1 + 2 + … + n in three worlds, Peano Lab, Lean → the book, chapter 4
→ Lecture 2 and the book
numerics
symbolic computation (CAS)
formal proof
Lecture 1 · outline
Organization

The course at WMI UAM

These slides were prepared for the course “Komputerowe rozwiązywanie problemów matematycznych”, taught in Polish at Wydział Matematyki i Informatyki UAM (Poznań) in the winter semester 2026/27. Dates, rooms, lab groups and all other formal course information are available only in Polish:

Materials: bnaskrecki.faculty.wmi.amu.edu.pl/math-comp/en — course book (Jupyter Book), slides, applets, lab problem sets.
Lecture 1 · organization Strona kursu (in Polish) →
Organization

Assessment

The requirements for passing the course and the grading scale follow the syllabus. They apply to the course taught at WMI UAM and are published only in Polish:

Lecture 1 · organization Warunki zaliczenia (in Polish) →
Organization

What lies ahead: topics and literature

Course contents (syllabus)

The official list of topics is part of the syllabus, which is available only in Polish:

Literature

  • P. Zimmermann et al., Computational Mathematics with SageMath, SIAM 2018 (CC-BY-SA license, PDF available online)
  • J. von zur Gathen, J. Gerhard, Modern Computer Algebra, 3rd ed., Cambridge UP 2013
  • D. E. Knuth, The Art of Computer Programming
  • python.org · sympy.org · sagemath.org
Lecture: ideas and the “why”.
Lab: hands on the keyboard — the “how”.
Lecture 1 · organization Sylabus w skrócie (in Polish) →
Part I

Three worlds of computation

numerics · symbolic computation · formal proof

Warm-up: is $\sqrt{2}\cdot\sqrt{2} = 2$?

Numerics · Python float


>>> import math
>>> math.sqrt(2)**2
2.0000000000000004
>>> math.sqrt(2)**2 == 2
False
      

√2 ≈ 1.4142135623730951 — an approximation; rounding error ≈ 4.4·10⁻¹⁶.

Symbolic computation · SymPy


>>> import sympy as sp
>>> sp.sqrt(2)**2
2
>>> sp.sqrt(2)**2 == 2
True
      

√2 is a symbolic object; the rule $(\sqrt a)^2 = a$ gives an exact result.

Proof · Lean 4 + Mathlib


example (a : ℝ) (h : 0 ≤ a) :
    Real.sqrt a * Real.sqrt a = a :=
  Real.mul_self_sqrt h
      

A theorem for every $a \ge 0$, checked by the Lean kernel.

Three different questions: what is it approximately? · what is the exact result of the computation? · is it true for all $a$ — and why?
Lecture 1 · Part I — Three worlds Open in the book →

Three worlds — how they complement each other

Formal proof Lean 4 + Mathlib · Peano Lab “true for all n” Numerics float, NumPy, C “≈ 1.4142135623730951” Symbolic computation CAS: SymPy, SageMath “√2, n(n+1)/2” numerics suggests conjectures CAS finds formulas, certificates ✓ Lean checks proofs we test formulas on numbers, and generalize numbers to formulas You: question & idea Lecture 1 · Part I — Three worlds

Numerics vs. symbolic computation vs. proof

NumericsSymbolic computation (CAS)Formal proof
Objectsmachine numbers (float64)expressions, polynomials, exact numberspropositions and proofs (types and terms)
Answeran approximate valuean exact result or formula“true” + a checked proof
Guaranteenone, unless we bound the errormodulo the correctness of the program and the assumptionssmall kernel — small trusted base
Speedenormous (hardware, billions of operations/s)moderate; expressions “swell”slow; a lot of human work
Pitfallsrounding, loss of digits, overflowbranches of functions, assumptions, the heuristic simplifyhave we formalized the right statement?
ToolsPython float, NumPy, C, FortranSymPy, SageMath, Mathematica, Maple, Magma, PARI/GPLean 4 + Mathlib, Rocq, Isabelle, Peano Lab
A good mathematician-programmer knows which world they are working in at the moment — and what guarantee they can expect.
Lecture 1 · Part I — Three worlds Open in the book →
Part II

Working environment

VS Code · Python · Jupyter · SymPy · SageMath

Why Visual Studio Code?

  • One editor for everything: Python (.py), Jupyter notebooks (.ipynb), Markdown + $\LaTeX$, Lean 4, Git
  • free, for Windows, macOS and Linux
  • built-in terminal, code completion, debugger
  • the same environment in the lab and at home
Extensions (Ctrl/⌘+Shift+X):
✔ Python · ✔ Jupyter · ✔ Pylance (Microsoft)
optional: LaTeX Workshop · Lean 4
demo.ipynb — krpm — Visual Studio Code EXPLORER ▸ .venv demo.ipynb fib.py notatki.md Gauss.lean Integral of a polynomial ∫₀¹ x² dx = 1/3 Markdown [1] import sympy as sp x = sp.symbols('x') sp.integrate(x**2, (x, 0, 1)) output: 1/3 TERMINAL (.venv) $ pip install sympy Successfully installed sympy … Python 3.12 (.venv) · Jupyter · UTF-8
Lecture 1 · Part II — Environment Instructions in the book →

Installation: Python + a virtual environment

  1. Install VS Code (code.visualstudio.com) and Python 3 (python.org; on Windows, check “Add python.exe to PATH”).
  2. Create a course folder and a virtual environment, and install the libraries:

mkdir krpm && cd krpm
python3 -m venv .venv                 # Windows: py -m venv .venv
source .venv/bin/activate             # Windows: .venv\Scripts\activate
pip install sympy numpy matplotlib ipykernel
  

Alternative (faster): uv venv, then uv pip install sympy numpy matplotlib ipykernel.

  1. In VS Code: Ctrl/⌘+Shift+P → “Python: Select Interpreter” → .venv.
Virtual environment = a separate set of libraries for one project. We do not break the system Python, and the project is easy to reproduce on another computer.
Lecture 1 · Part II — Environment Instructions in the book →

A Jupyter notebook in VS Code — live demo

  • Notebook = code cells + text cells (Markdown + $\LaTeX$)
  • a .ipynb file; in the top right corner we select the kernel: .venv
  • Shift+Enter — run the cell and move on
  • formulas as in $\LaTeX$: $\int_0^1 x^2\,dx$ → $\int_0^1 x^2\,dx = \tfrac13$
  • Caution: the kernel state depends on the order in which the cells were run — before handing in your work: “Restart” and “Run All”

Demo — checklist

  • new folder, .venv, install SymPy
  • new notebook demo.ipynb, choose the kernel
  • cell: 2**100 and 0.1 + 0.2
  • Markdown cell with a heading and a formula
  • SymPy: sp.factor(x**4 - 1)
  • plot: matplotlib — a parabola
  • Restart → Run All → save
Lecture 1 · Part II — Environment Open in the book →

SymPy: a CAS as a Python library


import sympy as sp
x = sp.symbols('x')

sp.expand((x + 1)**3)               # x**3 + 3*x**2 + 3*x + 1
sp.factor(x**4 - 1)                 # (x - 1)*(x + 1)*(x**2 + 1)
sp.solve(x**2 - 2, x)               # [-sqrt(2), sqrt(2)]
sp.diff(sp.sin(x)*sp.exp(x), x)     # exp(x)*sin(x) + exp(x)*cos(x)
sp.integrate(1/(1 + x**2), x)       # atan(x)
sp.limit(sp.sin(x)/x, x, 0)         # 1
sp.Rational(1, 3) + sp.Rational(1, 6)   # 1/2
    
  • pure Python: pip install sympy
  • expressions are Python objects — they can be stored in variables and passed to functions
  • exact results: √2, π, 1/3 remain symbols
  • approximation only on demand: sp.N(sp.pi, 50)

Documentation and tutorial: sympy.org

Lecture 1 · Part II — Environment Open in the book →

SageMath — a system built on top of Python

SageMath Python + preparser + a common interface to many libraries PARI/GP FLINT Maxima Singular GAP NTL SymPy NumPy / SciPy matplotlib … and many more number theory fast arithmetic symbolic calculus polynomials, Gröbner group theory lattices, polynomials symbolic computation numerics plots sagemath.org

One language (Python), one convention — and underneath, decades of work by specialists from many fields.

Lecture 1 · Part II — Environment Open in the book →

SageMath: the preparser and how to run Sage


sage: 2^100                    # ^ to potęga!
1267650600228229401496703205376
sage: 1/3 + 1/6                # ułamek, nie float
1/2
sage: R.<x> = QQ[]             # pierścień Q[x]
sage: factor(x^4 - 1)
(x - 1) * (x + 1) * (x^2 + 1)
sage: preparse("R.<x> = QQ[]")
"R = QQ['x']; (x,) = R._first_ngens(1)"
sage: preparse("2^100 + 1/2")
'Integer(2)**Integer(100) + Integer(1)/Integer(2)'
      

The preparser translates Sage’s “mathematical” syntax into plain Python.

Where to run Sage?

  • SageMathCell — sagecell.sagemath.org: in the browser, no installation
  • CoCalc — cocalc.com: Sage/Jupyter notebooks in the cloud
  • Faculty JupyterHub — jupyter.wmi.amu.edu.pl
  • Locally — Linux, or WSL2 on Windows; on macOS, the SageMath app
In plain Python, 2^100 is XOR (= 102) and 1/3 is a float. In Sage — a power and a fraction.
Lecture 1 · Part II — Environment Open in the book →

The same task in three dialects

TaskPythonSymPySageMath
$2^{100}$2**100sp.Integer(2)**1002^100
→ 1267650600228229401496703205376 in all three (integers are exact)
$\tfrac13 + \tfrac16$1/3 + 1/6 → 0.5 (float!)sp.Rational(1, 3) + sp.Rational(1, 6) → 1/21/3 + 1/6 → 1/2
factor $x^4-1$— (none)sp.factor(x**4 - 1)
→ (x - 1)*(x + 1)*(x**2 + 1)
factor(x^4 - 1)
→ (x^2 + 1)*(x + 1)*(x - 1)
$x^2 = 2$math.sqrt(2)
→ 1.4142135623730951
sp.solve(x**2 - 2, x)
→ [-sqrt(2), sqrt(2)]
solve(x^2 - 2 == 0, x)
→ [x == -sqrt(2), x == sqrt(2)]
pitfall2^100 → 102 (XOR)in SymPy, too, ^ is not exponentiation — use **
Lecture 1 · Part II — Environment Open in the book →

Python for mathematicians (1): numbers


>>> 2**100              # int: dowolna precyzja
1267650600228229401496703205376
>>> 7 / 2, 7 // 2, 7 % 2
(3.5, 3, 1)
>>> -7 // 2, -7 % 2
(-4, 1)
>>> 2^100               # to NIE jest potęga!
102
      
Division with remainder: $a = (a \,/\!/\, b)\cdot b + a \,\%\, b$,  where $0 \le a \,\%\, b < b$ for $b > 0$.
^ is bitwise XOR; exponentiation is **:
$2 \oplus 100 = 0000010_2 \oplus 1100100_2 = 1100110_2 = 102$

>>> 0.1 + 0.2
0.30000000000000004
>>> from fractions import Fraction
>>> Fraction(1, 10) + Fraction(2, 10)
Fraction(3, 10)
>>> Fraction(0.1)       # co naprawdę jest w 0.1
Fraction(3602879701896397, 36028797018963968)
      

int — exact, no limit on digits; float — 64 bits, an approximation; Fraction — exact fractions.

Lecture 1 · Part II — Python for mathematicians Open in the book →

Python for mathematicians (2): sets, functions, loops

$\{\, n^2 : n \in \{1,\dots,10\},\ 2 \nmid n \,\}$ ⟷ [n**2 for n in range(1, 11) if n % 2]
→ [1, 9, 25, 49, 81]

def nwd(a, b):
    """Euklides: NWD(a, b) = NWD(b, a mod b)."""
    while b != 0:
        a, b = b, a % b
    return abs(a)

nwd(1071, 462)        # 21
    

def collatz(n):
    """Kroki do 1: n → n/2 lub 3n+1."""
    kroki = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else 3*n + 1
        kroki += 1
    return kroki

[collatz(n) for n in range(1, 11)]
# [0, 1, 7, 2, 5, 8, 16, 3, 19, 6]
collatz(27)                  # 111
    

Does collatz(n) terminate for every $n \ge 1$? — Nobody knows: the Collatz problem (1937) is open.

Lecture 1 · Part II — Python for mathematicians Open in the book →

Summary

✓Three worlds: numerics (fast, approximate), symbolic computation (exact), formal proof (certain).
✓Environment: VS Code + Python + Jupyter; SymPy (a library), SageMath (a system).
→In Lecture 2: how a computer algebra system works, and floating-point numbers and errors. The sum 1 + 2 + … + n in three worlds, Peano Lab and Lean: the book, chapter 4.

Before the lab

  • install VS Code, Python and the Python + Jupyter extensions
  • create .venv and install sympy numpy matplotlib ipykernel
  • run your first notebook: 2**100, sp.factor(x**4 - 1)
  • read the Lecture 1 chapters in the book
  • play with the applets and Peano Lab
Lecture 1 · Summary Installation instructions →

Thank you!

Next lecture: for the date, see Harmonogram (in Polish).
Lecture 2: how a computer algebra system works, floating-point numbers and errors. The sum 1 + 2 + … + n in Python, SymPy and Peano Lab: the book, chapter 4.

ESC slide overview · S speaker notes · ? keyboard shortcuts