Lab 2: SymPy and SageMath — first symbolic computations#

Duration: 90 min · Lecture: How does a computer algebra system work?

Learning goals#

After this session you will be able to:

  1. create symbols and expressions in SymPy and distinguish exact numbers (Integer, Rational, sqrt(2), pi) from approximate ones (Float);

  2. transform expressions (expand, factor, simplify, cancel, apart, together, collect), substitute (subs), and solve equations (solve, solveset);

  3. look “under the hood” of a computer algebra system (CAS): see the expression tree (srepr, .func, .args);

  4. control the precision of computations (N) and understand the role of assumptions (real=True, positive=True);

  5. compare the syntax of SymPy and SageMath;

  6. work through one example in three worlds: numerical, symbolic, and formal (a proof in Peano Lab).

Preparation

We use the environment from Lab 1 (.venv with the sympy package). Convention: import sympy as sp — this way it is immediately clear which functions come from SymPy. We avoid from sympy import *, because it brings in, among others, the single-letter names N, S, E, and I, which are easy to overwrite accidentally with a variable of your own (in B6 we name an integral I ourselves).

import sympy as sp
print("SymPy", sp.__version__)
x, y, z = sp.symbols('x y z')
SymPy 1.14.0

Part A — warm-up (≈ 25 min)#

A1. Symbols and expressions ★#

The function sp.symbols('x y z') in the cell above created three symbols, i.e., SymPy objects that stand for mathematical variables (as opposed to Python variables that store numbers). Operations on symbols produce expressions, and the notebook displays the value of the last expression in a cell as a mathematical formula:

e = (x + y)**3
e
\[\displaystyle \left(x + y\right)^{3}\]

The expression e stays in the form in which we entered it: SymPy does not multiply out parentheses on its own, because it cannot know which form we need. Expansion and factorization are performed on request:

sp.expand(e)
\[\displaystyle x^{3} + 3 x^{2} y + 3 x y^{2} + y^{3}\]
sp.factor(x**4 - 1)
\[\displaystyle \left(x - 1\right) \left(x + 1\right) \left(x^{2} + 1\right)\]

Exercise. Expand \((x + y + z)^3\). How many terms does the result have? (Hint: len(wyrazenie.args).) Compare the answer with the number of monomials of degree \(3\) in three variables, which equals \(\binom{3+2}{2}\).

# TWÓJ KOD
...

A2. Exact and approximate numbers ★#

Numbers in SymPy are either exact (integers, rationals, roots, constants such as \(\pi\)) or approximate (Float). The biggest pitfall lurks at the interface with Python: a fraction written with the ordinary / on integers is computed by Python before SymPy ever sees it.

print(1/3, type(1/3))                  # to oblicza Python: float!
print(sp.Rational(1, 3), sp.S(1)/3)    # liczby wymierne SymPy
print(x + 1/3)                         # pułapka: 1/3 policzył Python, zanim SymPy zobaczył ułamek
print(x + sp.Rational(1, 3))
0.3333333333333333 <class 'float'>
1/3 1/3
x + 0.333333333333333
x + 1/3

Exact numbers behave just as they do in mathematics — irrational and complex ones included:

sp.sqrt(8), sp.sqrt(2)**2, sp.pi, sp.E, sp.I**2
(2*sqrt(2), 2, pi, E, -1)

SymPy immediately turns \(\sqrt{8}\) into \(2\sqrt{2}\), and \((\sqrt{2})^2\) into \(2\) — this is automatic simplification, performed as soon as the expression is created. Approximate values, with any number of digits, are obtained with the function sp.N (or the method .evalf()):

sp.N(sp.sqrt(2), 50)
\[\displaystyle 1.4142135623730950488016887242096980785696718753769\]

The function sp.nsimplify tries to guess the exact value of an approximate number — this is a heuristic, not a proof:

sp.nsimplify(0.333333333333333), sp.nsimplify(1.618033988749895, [sp.sqrt(5)])
(1/3, 1/2 + sqrt(5)/2)

Exercise. Compute \(\pi\) to \(100\) decimal places. What is the hundredth digit after the decimal point? Note: sp.N rounds the last digit it prints. Compare the hundredth digit read off from sp.N(sp.pi, 101) and from sp.N(sp.pi, 110), and explain the difference.

# TWÓJ KOD
...

A3. Transforming expressions ★#

Function

What it does

Example

sp.expand

multiplies out parentheses

\((x+1)^2 \to x^2 + 2x + 1\)

sp.factor

factors (over \(\mathbb{Q}\) by default)

\(x^4 - 1 \to (x-1)(x+1)(x^2+1)\)

sp.cancel

cancels common factors in a rational function

\(\frac{x^2-1}{x-1} \to x + 1\)

sp.apart

decomposes into partial fractions

\(\frac{1}{x(x+1)} \to \frac{1}{x} - \frac{1}{x+1}\)

sp.together

combines over a common denominator

the inverse of apart

sp.collect

collects terms with respect to powers of a variable

\(x^2 + xy + x \to x^2 + x(y + 1)\)

sp.simplify

tries many methods and picks the “simplest” result

\(\sin^2 x + \cos^2 x \to 1\)

sp.cancel((x**2 - 1)/(x - 1))
\[\displaystyle x + 1\]

Warning

cancel returns \(x + 1\), even though the expression \(\frac{x^2-1}{x-1}\) is undefined at \(x = 1\). A CAS treats it as an element of the field of rational functions \(\mathbb{Q}(x)\), not as a function on a specific domain. This is one of the challenges in designing computer algebra systems that we discussed in the lecture.

sp.apart(1/(x*(x + 1))), sp.together(1/x - 1/(x + 1))
(-1/(x + 1) + 1/x, 1/(x*(x + 1)))

The functions apart and together work in opposite directions: the first decomposes a rational function into partial fractions, the second combines a sum of fractions over a common denominator. Composing the two gives the same rational function, but not necessarily the same written form. The function collect arranges an expression by powers of a chosen variable — below, we treat the expression as a polynomial in the variable \(x\) with coefficients depending on \(y\):

sp.collect(sp.expand((x + y + 1)**2), x)
\[\displaystyle x^{2} + x \left(2 y + 2\right) + y^{2} + 2 y + 1\]

The function simplify recognizes the Pythagorean trigonometric identity, and trigonometric transformations work in both directions: expand_trig expands trigonometric functions of sums and multiples of an angle, and trigsimp tries to collapse the expression back:

sp.simplify(sp.sin(x)**2 + sp.cos(x)**2), sp.expand_trig(sp.sin(2*x)), sp.trigsimp(2*sp.sin(x)*sp.cos(x))
(1, 2*sin(x)*cos(x), sin(2*x))

The result of factorization depends on the field of coefficients. Over \(\mathbb{Q}\), the polynomial \(x^2 - 2\) is irreducible; after adjoining \(\sqrt2\) (the extension option), it splits into linear factors, and the option gaussian=True allows coefficients from \(\mathbb{Q}(i)\):

sp.factor(x**2 - 2), sp.factor(x**2 - 2, extension=sp.sqrt(2)), sp.factor(x**4 - 1, gaussian=True)
(x**2 - 2, (x - sqrt(2))*(x + sqrt(2)), (x - 1)*(x + 1)*(x - I)*(x + I))

Exercise. (a) Factor \(x^6 - 1\) over \(\mathbb{Q}\). (b) Decompose \(\dfrac{1}{x^4 - 1}\) into partial fractions. (c) Simplify \(\dfrac{x^3 - 1}{x^2 - 1}\) by canceling common factors. (d) Factor \(x^4 + 4\) over \(\mathbb{Q}\) (the Sophie Germain identity!).

# TWÓJ KOD
...

A4. The expression tree: how SymPy stores formulas ★#

The function srepr shows the full structure of an expression, and the attributes func and args show the root of the tree (the kind of operation) and its subtrees:

e = x**2 + 2*x + 1
print(sp.srepr(e))
print(e.func, e.args)
Add(Pow(Symbol('x'), Integer(2)), Mul(Integer(2), Symbol('x')), Integer(1))
<class 'sympy.core.add.Add'> (1, x**2, 2*x)

The tuple e.args begins with the constant \(1\), even though we typed it last: SymPy stores the arguments of a sum in an order of its own choosing. (The function srepr, like ordinary printing, arranges the terms by decreasing powers, which is why, in the first line, the order looks like the one we typed.) Subtraction and division do not have nodes of their own:

print(sp.srepr(x - y))    # nie ma osobnego węzła „odejmowanie”...
print(sp.srepr(x / y))    # ...ani „dzielenie”
Add(Symbol('x'), Mul(Integer(-1), Symbol('y')))
Mul(Symbol('x'), Pow(Symbol('y'), Integer(-1)))

Internally, \(x - y\) is Add(x, Mul(-1, y)), and \(x/y\) is Mul(x, Pow(y, -1)). The arguments of sums and products are stored in a fixed order, so x + y and y + x have the same tree, and the comparison x + y == y + x gives True. This normalization allows expressions that are equal “up to commutativity” to be recognized quickly, but it is not a canonical form in the sense of the lecture: \((x+1)^2\) and \(x^2 + 2x + 1\) have different trees, even though they denote the same polynomial. You can explore expression trees in the “Expression tree” applet.

The function sp.preorder_traversal traverses the tree in preorder (first the node, then each of its subtrees in turn). Let us print the type and content of every node of the tree of \(x^2 + 2x + 1\):

for w in sp.preorder_traversal(e):
    print(type(w).__name__, "\t", w)
Add 	 x**2 + 2*x + 1
One 	 1
Pow 	 x**2
Symbol 	 x
Integer 	 2
Mul 	 2*x
Integer 	 2
Symbol 	 x

The tree has \(8\) nodes. The number \(2\) occurs in it twice as a separate leaf (the exponent and the coefficient), and the constant \(1\) has its own class One: SymPy stores the most common constants as unique instances (singletons).

Exercise. Draw the expression tree of \(\sin^2 x + \cos^2 x\) on paper and compare it with the output of sp.srepr. How many nodes does this tree have? Count them with a program as well.

# TWÓJ KOD
...

A5. Substitution and equations ★#

The method subs substitutes numbers or other expressions for symbols; with a dictionary, several values can be substituted at once:

e = x**2 + y
e.subs(x, 3), e.subs({x: 1, y: 2})
(y + 9, 3)

The function solve solves algebraic equations and returns a list of solutions, in this case exact ones. An expression given without an equals sign is set equal to zero:

sp.solve(x**2 - x - 1, x)
[1/2 - sqrt(5)/2, 1/2 + sqrt(5)/2]

The equation \(\sin x = \tfrac12\) has infinitely many real solutions. No list can hold them all, so we use the function solveset, which returns a set — here \(\{\tfrac{\pi}{6} + 2k\pi : k \in \mathbb{Z}\} \cup \{\tfrac{5\pi}{6} + 2k\pi : k \in \mathbb{Z}\}\):

sp.solveset(sp.sin(x) - sp.Rational(1, 2), x, domain=sp.S.Reals)
\[\displaystyle \left\{2 n \pi + \frac{\pi}{6}\; \middle|\; n \in \mathbb{Z}\right\} \cup \left\{2 n \pi + \frac{5 \pi}{6}\; \middle|\; n \in \mathbb{Z}\right\}\]

The notation ImageSet(Lambda(_n, 2*_n*pi + pi/6), Integers) denotes the image of the set \(\mathbb{Z}\) under the function \(n \mapsto 2n\pi + \frac{\pi}{6}\), i.e., the first of the two sets given above.

A system of equations is given as a list of expressions (each set equal to zero) and a list of unknowns:

sp.solve([x + y - 3, x - y - 1], [x, y])
{x: 2, y: 1}

Exercise. Solve the equation \(x^3 - 6x^2 + 11x - 6 = 0\) and check, by substituting the numbers obtained into the polynomial, that they are roots. Also solve the equation \(x^3 = 2\) with sp.solve and with sp.solveset(..., domain=sp.S.Reals). How do the results differ?

# TWÓJ KOD
...

A6. Assumptions: \(\sqrt{x^2}\) is not always \(x\) ★#

SymPy treats a symbol without assumptions as an arbitrary complex number. Assumptions (real, positive, integer, …) are given when the symbol is created, and they determine which simplifications are allowed:

t = sp.Symbol('t')                       # domyślnie: dowolna liczba zespolona
t_r = sp.Symbol('t', real=True)
t_p = sp.Symbol('t', positive=True)
sp.sqrt(t**2), sp.sqrt(t_r**2), sp.sqrt(t_p**2)
(sqrt(t**2), Abs(t), t)

The result depends on the assumptions. For \(t > 0\) we have \(\sqrt{t^2} = t\). For real \(t\) the correct formula is \(\sqrt{t^2} = |t|\) (e.g., for \(t = -1\) we have \(\sqrt{t^2} = 1 \ne t\)), hence Abs(t). For complex \(t\) the square root denotes the principal branch, so \(\sqrt{t^2}\) equals \(t\) or \(-t\), depending on where \(t\) lies in the complex plane; there is no simple formula, which is why SymPy does not simplify \(\sqrt{t^2}\) without assumptions. A CAS that “simplified” too boldly would give wrong results.

Exercise. Check what SymPy does with the expressions \(\ln(e^{t})\) and \((\sqrt{t})^2\) (compare them with \((t^2)^{1/2} = \sqrt{t^2}\) from the example above) for a symbol without assumptions, with real=True, and with positive=True. Explain the differences.

# TWÓJ KOD
...

A7. SymPy vs. SageMath ★#

SageMath is a system built on Python that brings many specialized libraries (including PARI/GP, FLINT, Maxima, Singular, and GAP) together under a common interface. SymPy is a library written in pure Python — it installs with a single command, pip install sympy. Sage is not installed in our .venv environment; the easiest way to try it is in the browser: SageMathCell https://sagecell.sagemath.org or CoCalc https://cocalc.com.

Task

SymPy

SageMath

symbols

x, y = sp.symbols('x y')

x, y = var('x y') (the symbol x is predefined)

power

x**3

x^3 or x**3

the number \(\frac12\)

sp.Rational(1, 2) (because 1/2 is the float number 0.5!)

1/2 (a rational number)

expansion, factorization

sp.expand(e), sp.factor(e)

e.expand(), factor(e)

polynomial ring

R = sp.QQ[x] (a polynomial in it: sp.Poly(x**4 - 1, x, domain='QQ'))

R.<x> = QQ[]

equations

sp.solve(x**2 - 2, x)

solve(x^2 - 2, x)

approximation

sp.N(sp.pi, 50)

pi.n(digits=50)

Fibonacci numbers

sp.fibonacci(10)

fibonacci(10)

matrix, determinant

sp.Matrix([[1, 2], [3, 4]]).det()

matrix(QQ, [[1, 2], [3, 4]]).det()

definite integral

sp.integrate(sp.sin(x), (x, 0, sp.pi))

integrate(sin(x), x, 0, pi)

Before running code, Sage preprocesses it (preparsing): it replaces ^ with **, integer literals with Integer objects (which is why 1/2 is a fraction and not a float), and the notation R.<t> = QQ[] with ordinary function calls. An example (run it in SageMathCell — in plain Python this code does not work):

# SageMath
R.<t> = QQ[]              # pierścień wielomianów Q[t]
f = t^4 - 1
print(f.factor())         # rozkład nad Q
print(1/2 + 1/3)          # 5/6 — liczba wymierna, bez float
print(pi.n(digits=30))
print(fibonacci(100))

Exercise. Run the code above in SageMathCell, then write its SymPy equivalent in the cell below.

# TWÓJ KOD
...

Part B — main exercises (≈ 40 min)#

B1. Symbolic sums ★#

The function summation computes sums in closed form. Let us compute the sums of the first, second, and third powers of the numbers \(1, 2, \dots, n\):

k = sp.symbols('k', integer=True, positive=True)
n = sp.symbols('n', integer=True, positive=True)
S1 = sp.summation(k, (k, 1, n))
S2 = sp.summation(k**2, (k, 1, n))
S3 = sp.summation(k**3, (k, 1, n))
S1, sp.factor(S2), sp.factor(S3)
(n**2/2 + n/2, n*(n + 1)*(2*n + 1)/6, n**2*(n + 1)**2/4)

Note that \(\sum_{k=1}^n k^3 = \left(\sum_{k=1}^n k\right)^2\) (Nicomachus of Gerasa).

Exercise. (a) Verify this identity symbolically. (b) Compute \(\sum_{k=1}^n k^4\) and factor it. (c) Compute \(\sum_{k=1}^{n} (2k - 1)\), \(\sum_{j=0}^{n} \binom{n}{j}\), and \(\sum_{j=0}^{n} q^j\). What does a result of type Piecewise mean?

# TWÓJ KOD
...

B2. The last digit of \(A_{1000}\) ★★#

For every \(n \ge 0\) there exist uniquely determined integers \(A_n, B_n\) such that \((1 + \sqrt{2})^n = A_n + B_n\sqrt{2}\) (why do they exist, and why are they unique?).

Exercise.

(a) Find the last digit of \(A_{1000}\). Hint: sp.expand((1 + sp.sqrt(2))**1000), followed by the method .coeff(sp.sqrt(2), 0). How many digits does \(A_{1000}\) have?

(b) Check that \(A_n^2 - 2B_n^2 = (-1)^n\) for \(n \le 20\) (Pell’s equation).

(c) Justify the recurrence \(A_{n+1} = A_n + 2B_n\), \(B_{n+1} = A_n + B_n\) and use it to compute \(A_{1000} \bmod 10\) with integers only (and remainders modulo \(10\)).

(d) Analysis: print \(A_n \bmod 10\) for \(n = 0, 1, \dots, 30\). What do you notice? (This will be useful in exercise Z3 at the end of the set.)

# TWÓJ KOD
...

B3. Binet’s formula and Cassini’s identity ★★#

Binet’s formula: \(F_n = \dfrac{\varphi^n - \psi^n}{\sqrt5}\), where \(\varphi = \frac{1+\sqrt5}{2}\), \(\psi = \frac{1-\sqrt5}{2}\). Cassini’s identity: \(F_n^2 - F_{n+1}F_{n-1} = (-1)^{n-1}\) for \(n \ge 1\).

phi = (1 + sp.sqrt(5)) / 2
psi = (1 - sp.sqrt(5)) / 2

def F(m):
    return (phi**m - psi**m) / sp.sqrt(5)

[sp.expand(F(m)) for m in range(11)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Exercise.

(a) Check that, after expansion (sp.expand), the values F(m) agree with sp.fibonacci(m) for \(0 \le m \le 30\), and that Cassini’s identity holds for \(n = 1, \dots, 30\) (using integer arithmetic).

(b) Try to “prove” the identity symbolically: for the symbol m = sp.symbols('m', integer=True), simplify the expression wyr = F(m)**2 - F(m+1)*F(m-1) - (-1)**(m-1) with sp.simplify. Do you get \(0\)?

(c) Help the system: sp.simplify(sp.powsimp(sp.expand(wyr), force=True)). Read in the documentation (help(sp.powsimp)) what the option force=True does and why it can be dangerous. Why is it legitimate to use it here?

(d) Another strategy: introduce new symbols \(A = \varphi^m\), \(B = \psi^m\) and write the left-hand side of the identity as a rational expression in \(A, B\) (e.g., \(\varphi^{m+1} = \varphi A\), \(\psi^{m-1} = B/\psi\)). Simplify it. How do you obtain \((-1)^{m-1}\) from the result \(-AB\)?

(e) Analysis: which of the steps (a)–(d) are proofs, and which are only verifications?

# TWÓJ KOD
...

B4. Vieta’s formulas ★★#

The numbers \(\alpha, \beta\) are the roots of the polynomial \(x^2 + mx + 1\). Express \(\dfrac{1}{\alpha^3} + \dfrac{1}{\beta^3}\) as a function of the parameter \(m\).

Exercise. Solve this problem in three ways and compare the results:

(a) directly: find the roots with sp.solve, compute the expression, and simplify it;

(b) Vieta’s formulas: \(\alpha + \beta = -m\), \(\alpha\beta = 1\), and \(\alpha^3 + \beta^3 = (\alpha+\beta)^3 - 3\alpha\beta(\alpha+\beta)\);

(c) the resultant: the polynomial sp.resultant(x**2 + m*x + 1, y*x**3 - 1, x), regarded as a polynomial in the variable \(y\), has the roots \(1/\alpha^3\) and \(1/\beta^3\) — why? Read off the sum of the roots from Vieta’s formulas.

(d) Check the result numerically for \(m = 3\).

# TWÓJ KOD
...

B5. A number satisfying \(m = \dfrac{1}{1+m}\) ★#

The number \(m\) is equal to the reciprocal of \(m + 1\). Find \(m^{10}\).

Exercise. (a) Solve the equation and compute \(m^{10}\) exactly for both solutions (sp.expand, sp.radsimp). (b) Compute the remainder of \(x^{10}\) upon division by \(x^2 + x - 1\): sp.rem(x**10, x**2 + x - 1, x). Explain why \(m^{10} = 34 - 55m\). (c) Print the remainders of \(x^k\) upon division by \(x^2 + x - 1\) for \(k = 0, 1, \dots, 12\). What numbers do you see? (This will be useful in exercise Z1 at the end of the set.)

# TWÓJ KOD
...

B6. Limits, derivatives, and integrals ★#

SymPy computes limits, derivatives, and integrals symbolically — the result is exact, provided it can be found at all. Two classical limits:

N_ = sp.symbols('N', positive=True)
sp.limit(sp.sin(x)/x, x, 0), sp.limit((1 + 1/N_)**N_, N_, sp.oo)
(1, E)

SymPy computes the derivative of a product using the formula \((fg)' = f'g + fg'\):

sp.diff(sp.exp(x)*sp.sin(x), x)
\[\displaystyle e^{x} \sin{\left(x \right)} + e^{x} \cos{\left(x \right)}\]

SymPy also computes definite integrals, improper ones included. Here they are \(\int_0^\infty x e^{-x}\,dx = 1\) and the Gaussian integral \(\int_{-\infty}^{\infty} e^{-x^2}\,dx = \sqrt{\pi}\):

sp.integrate(x*sp.exp(-x), (x, 0, sp.oo)), sp.integrate(sp.exp(-x**2), (x, -sp.oo, sp.oo))
(1, sqrt(pi))

Now let us compute the indefinite integrals of two innocent-looking functions:

sp.integrate(sp.exp(-x**2), x), sp.integrate(sp.sin(x)/x, x)
(sqrt(pi)*erf(x)/2, Si(x))

The functions \(e^{-x^2}\) and \(\frac{\sin x}{x}\) have no elementary antiderivatives — this is Liouville’s theorem (1835), not a weakness of the program; algorithms such as the Risch algorithm can decide such questions. SymPy expresses the result in terms of the special functions \(\operatorname{erf} x = \frac{2}{\sqrt{\pi}}\int_0^x e^{-t^2}\,dt\) and \(\operatorname{Si} x = \int_0^x \frac{\sin t}{t}\,dt\), which are defined precisely as such integrals.

Things are different with the integral \(\int_0^1 x^x\,dx\); let us check what integrate returns and what the type of the result is:

I = sp.integrate(x**x, (x, 0, 1))
I, type(I).__name__
(Integral(x**x, (x, 0, 1)), 'NonElementaryIntegral')

SymPy leaves the integral \(\int_0^1 x^x\,dx\) unevaluated, but it returns an object of the special type NonElementaryIntegral: the part of the Risch algorithm implemented in SymPy has proved that the function \(x^x\) has no elementary antiderivative. (Curiously, sp.N does not compute the numerical value of such an object — for numerical computations, use the ordinary integral sp.Integral(x**x, (x, 0, 1)).)

Exercise. (a) Compute the derivative of the function \(x^x\). (b) Compute \(\int_0^\infty e^{-x^2}\,dx\). (c) Compute numerically, to 30 digits, the integral \(\int_0^1 x^x\,dx\) (sp.N(sp.Integral(x**x, (x, 0, 1)), 30)) and the sum \(\sum_{k=1}^{\infty} (-1)^{k+1} k^{-k}\) (sp.Sum(...), then sp.N). Compare. This is the so-called “sophomore’s dream” (J. Bernoulli, 1697). Is agreement to 30 digits a proof?

# TWÓJ KOD
...

B7. From formula to plot: lambdify ★#

A SymPy expression is convenient for transformations but slow for computations at thousands of points. The function lambdify turns it into an ordinary Python function that works on NumPy arrays — a bridge between the symbolic and the numerical world:

import numpy as np
import matplotlib.pyplot as plt

f = sp.sin(x) / x
f_num = sp.lambdify(x, f, "numpy")      # wyrażenie SymPy → szybka funkcja NumPy
xs = np.linspace(-20, 20, 2000)         # parzysta liczba punktów: omijamy x = 0
plt.figure(figsize=(8, 3))
plt.plot(xs, f_num(xs))
plt.title(r"$\sin x / x$"); plt.grid(alpha=0.3)
plt.show()
../_images/60d300e4e7ff80309c931d66705da371fee03ff79275c448f8eaeaa5b7115573.png

Exercise. (a) On the interval \([-2\pi, 2\pi]\), plot the function \(\sin x\) together with its Taylor polynomials of degrees \(1, 3, 5, 7, 9\) (sp.series(sp.sin(x), x, 0, st + 1).removeO(), where st is the degree); set the range of the \(y\)-axis to \([-2, 2]\). (b) What is the smallest degree for which the Taylor polynomial approximates \(\sin x\) on \([-\pi, \pi]\) with an error less than \(10^{-6}\)? Determine it numerically (np.max(np.abs(...))).

# TWÓJ KOD
...

B8. Is \(e^{\pi\sqrt{163}}\) an integer? ★★#

Let us compare three computations of the same number: in float arithmetic and in SymPy with \(15\) and \(40\) significant digits:

import math
R = sp.exp(sp.pi * sp.sqrt(163))
print(math.exp(math.pi * math.sqrt(163)))   # arytmetyka float
print(sp.N(R, 15))
print(sp.N(R, 40))
2.6253741264076826e+17
2.62537412640769e+17
262537412640768743.9999999999992500725972

The number \(e^{\pi\sqrt{163}}\) (known as Ramanujan’s constant) is transcendental (this follows from the Gelfond–Schneider theorem), and yet it differs from an integer by less than \(10^{-12}\). Note also that the result computed in float arithmetic differs from the true value by several hundred!

Exercise. (a) Explain where such a large error in float arithmetic comes from (hint: what is the absolute error of the computed exponent \(\pi\sqrt{163} \approx 40\), and what does the exponential function do to it?). (b) Compute \(e^{\pi\sqrt{d}}\) to \(40\) significant digits for \(d \in \{19, 43, 67, 163\}\). How close to integers are these values? (The numbers \(19\), \(43\), \(67\), and \(163\) are so-called Heegner numbers, and the closeness of \(e^{\pi\sqrt{d}}\) to integers reflects deep algebraic number theory.)

# TWÓJ KOD
...

B9. Expression swell ★★#

We measure the size of an expression by the number of nodes in its tree.

Exercise. (a) Write a function liczba_wezlow(e) that counts the nodes (use sp.preorder_traversal). (b) Compare the number of nodes of the expression \((x+y)^n\) and of its expansion for \(n = 1, \dots, 20\) — draw a plot. (c) Compare the number of nodes of \(x^n - 1\) and of sp.factor(x**n - 1) for \(n \in \{2, 6, 12, 30, 60\}\). Analysis: is there a single “simplest” form of an expression? What does “simplify” mean in practice?

# TWÓJ KOD
...

Part C — optional challenges#

C1. Cube roots and branches ★★★#

Cardano’s formulas yield the identity \(\sqrt[3]{2+\sqrt5} + \sqrt[3]{2-\sqrt5} = 1\) (for real roots). Let us check it in SymPy by computing the difference between the two sides numerically:

w = sp.cbrt(2 + sp.sqrt(5)) + sp.cbrt(2 - sp.sqrt(5)) - 1
sp.N(w)
\[\displaystyle 0.927050983124842 + 0.535233134659635 i\]

The result is not zero, because \(2 - \sqrt5 < 0\), and sp.cbrt of a negative number \(a\) is the principal value of the cube root, i.e., the complex number \(|a|^{1/3} e^{i\pi/3}\), not the real root.

Exercise. (a) Compare sp.N(sp.cbrt(-8)) and sp.real_root(-8, 3). (b) Repeat the computation for the real roots: compute s_expr = sp.real_root(2 + sp.sqrt(5), 3) + sp.real_root(2 - sp.sqrt(5), 3) and simplify s_expr - 1. (c) Prove the identity on paper: for \(u = \sqrt[3]{2+\sqrt5}\), \(v = \sqrt[3]{2-\sqrt5}\), and \(s = u + v\) we have \(u^3 + v^3 = 4\) and \(uv = -1\), so \(s^3 = 4 - 3s\). Factor \(s^3 + 3s - 4\) and conclude that \(s = 1\). (d) Compare with the output of sp.minimal_polynomial(s_expr, x).

# TWÓJ KOD
...

C2. Quotient rings and Gröbner bases ★★★#

Exercise B4 has a “lightning-fast” solution in SageMath — a computation in the quotient ring \(\mathbb{Q}[a, b, m]/(ab - 1,\ a + b + m)\):

# SageMath (np. https://sagecell.sagemath.org) — ten kod NIE działa w czystym Pythonie
R.<aa,bb,mm> = PolynomialRing(QQ, 3)
I = R.ideal([aa*bb - 1, aa + bb + mm])          # relacje: αβ = 1, α + β = -m
S.<abar,bbar,mbar> = R.quotient_ring(I)
1/abar^3 + 1/bbar^3                              # wynik: wielomian zmiennej mbar

In SymPy, we carry out the same computation using a Gröbner basis of the ideal of relations and reducing the polynomial modulo this basis.

Exercise. (a) Create the symbols a, b, m = sp.symbols('a b m') and compute G = sp.groebner([a*b - 1, a + b + m], a, b, m, order='lex'). (b) Since \(ab = 1\), we have \(\frac{1}{a^3} + \frac{1}{b^3} = a^3 + b^3\) — reduce this polynomial: G.reduce(a**3 + b**3) returns a pair (list of quotients, remainder), and the result of the reduction is the remainder. Compare with the result of B4. (c) Using the same method, express \(\alpha^5 + \beta^5\) in terms of \(m\).

# TWÓJ KOD
...

C3. Power sums — Faulhaber’s formula ★★★#

Exercise. (a) For \(p = 0, 1, \dots, 10\), compute \(S_p(n) = \sum_{k=1}^{n} k^p\) and factor the result. (b) Print the coefficients of the polynomial \(S_p(n)\) (sp.Poly(S, n).all_coeffs()). What is the leading coefficient? And the next one? (c) Check that for odd \(p \ge 3\) the polynomial \(S_p(n)\) is divisible by \(n^2(n+1)^2\). (d) Compare the coefficient of \(n\) with the Bernoulli number sp.bernoulli(p). (This will be useful in exercise Z2 at the end of the set.)

# TWÓJ KOD
...

Part D — one example, three worlds (≈ 15 min or at home)#

In the lecture we compared three ways of “knowing” that

\[1 + 2 + \dots + n = \frac{n(n+1)}{2}.\]

Now you will go through them on your own: numerically (we check cases — and watch out for machine arithmetic), symbolically (a CAS transforms formulas according to algorithms we trust), and formally (a proof checked by the kernel of a proof assistant).

D1. The numerical world ★#

Exercise.

(a) Using Python integers, check that sum(range(1, n + 1)) == n*(n + 1)//2 for all \(n \le 2000\).

(b) Now sum in single-precision arithmetic: start with s = np.float32(0) and add the successive numbers \(1, 2, 3, \dots\), rounding to the type np.float32 after each addition, i.e., s = np.float32(s + np.float32(i)). What is the smallest \(n\) for which the result first differs from \(n(n+1)/2\)? What is the “machine” sum then, and what is the true one?

(c) Analysis: compare the sum obtained with the number \(2^{24} = 16{,}777{,}216\). The float32 type has a 24-bit significand — which integers can it store exactly? Why is the wrong value even?

(d) Why is the same computation in float64 arithmetic (an ordinary float) guaranteed to be exact as long as \(n(n+1)/2 \le 2^{53}\), i.e., for \(n \le 134{,}217{,}727\)?

# TWÓJ KOD
...

D2. The symbolic world ★#

In the symbolic world we do not check cases; instead, we ask the CAS for a formula:

k, n = sp.symbols('k n', integer=True, positive=True)
S = sp.summation(k, (k, 1, n))
S, sp.factor(S)
(n**2/2 + n/2, n*(n + 1)/2)

SymPy returns \(\frac{n^2}{2} + \frac{n}{2} = \frac{n(n+1)}{2}\).

Exercise.

(a) In the same way, compute \(\sum_{k=1}^n k^2\) and \(\sum_{k=1}^n k^3\) and factor the results.

(b) Check the induction step symbolically: for \(T(n) = \frac{n(n+1)}{2}\), compute sp.simplify(T(n + 1) - T(n) - (n + 1)).

(c) Analysis: the result of (b) looks like a proof by induction. Why is it rather a pseudo-proof? Point out what we trust (the implementations of summation and simplify), what we have not checked (the base case, the induction principle itself, the correctness of the transformations), and what is missing (a certificate that someone could verify independently).

# TWÓJ KOD
...

D3. The formal world: a proof in Peano Lab ★ – ★★★#

Peano Lab is a simple system for proving theorems of Peano arithmetic in its intuitionistic version (Heyting arithmetic), running in the browser: https://bnaskrecki.faculty.wmi.amu.edu.pl/peano-lab/. Its language contains only \(0\), the successor \(S\), addition, and multiplication — there is no summation symbol \(\Sigma\) and no division. That is why the honest version of Gauss’s formula in this language is the statement that \(n(n+1)\) is even, i.e., that \(\frac{n(n+1)}{2} \in \mathbb{N}\):

\[\forall n\ \exists x\ \ n \cdot (n+1) = 2 \cdot x.\]

Each proof step (tactic) builds a piece of a certificate, and the command qed passes the whole certificate to an independent kernel, which checks it using only the rules of logic and equality, the axioms PA1–PA6, and the induction schema (type pa axioms to see them).

Open Peano Lab with this theorem and enter the commands one at a time (or paste the whole script using the paste multiline proof button):

pa prove forall n. exists x. n * (n + 1) = 2 * x
induction n
exists 0
ring
cases IH
exists x + S n
trans n * (n + 1) + 2 * S n
ring
rewrite IH_witness
ring
qed

What happens at each step?

  • induction n — proof by induction: two goals arise, the base case (\(n = 0\)) and the induction step (with the induction hypothesis IH).

  • exists 0, ring — in the base case the witness is \(x = 0\), since \(0 \cdot (0 + 1) = 2 \cdot 0\); the polynomial identity is closed by the ring tactic.

  • cases IH — we unpack the induction hypothesis: we get a witness \(x\) and the equation IH_witness: \(n(n+1) = 2x\).

  • exists x + S n — the witness for \(S\,n = n + 1\) is \(x + (n + 1)\), since \((n+1)(n+2) = n(n+1) + 2(n+1)\).

  • trans n * (n + 1) + 2 * S n — via the intermediate expression, we split the goal \(S\,n \cdot (S\,n + 1) = 2 \cdot (x + S\,n)\) into two equations; the first one, \(S\,n \cdot (S\,n + 1) = n(n+1) + 2 \cdot S\,n\), is closed by ring.

  • rewrite IH_witness, ring — in the second equation we replace \(n(n+1)\) with \(2x\) and close the identity \(2x + 2 \cdot S\,n = 2 \cdot (x + S\,n)\).

  • qed — the independent kernel checks the whole certificate against the original theorem, and Peano Lab responds with the message No open goals. QED. The command script then prints the report Independent kernel check: PASS (22847 certificate nodes): the kernel check has passed, and the certificate has \(22{,}847\) nodes.

The proof is constructive: the witness satisfies \(x_0 = 0\) and \(x_{n+1} = x_n + (n + 1)\), so \(x_n = 0 + 1 + \dots + n\) — the proof “contains” an algorithm for computing the sum!

Exercises (you do them in the browser, in Peano Lab — not in this notebook):

  1. ★ Warm-up: prove forall n. 0 + n = n (script: pa prove forall n. 0 + n = n, induction n, ring, ring, qed) and forall n. exists x. n + n = 2 * x (pa prove forall n. exists x. n + n = 2 * x, intro n, exists n, ring, qed). Why does the first theorem require induction, even though \(n + 0 = n\) is axiom PA3?

  2. ★ Reproduce the proof of Gauss’s formula given above. After qed, type script and read off the size of the certificate.

  3. ★★ Adapt the proof to the sum of squares: forall n. exists x. n * (n + 1) * (2 * n + 1) = 6 * x. Hint: what is the witness for \(n + 1\), given that \(\sum_{k=1}^{n+1} k^2 = \sum_{k=1}^{n} k^2 + (n+1)^2\)? What intermediate expression should you give to trans?

  4. ★★★ Prove the theorem for the sum of cubes in the same way: forall n. exists x. n * n * (n + 1) * (n + 1) = 4 * x.

  5. What happens if you give a wrong witness, e.g., exists x + n in the proof of Gauss’s formula? Try it and describe the message.

  6. In the Markdown cell below, explain in your own words how the witness \(x\) in the proofs from exercises 2–4 is related to the sums \(\sum k\), \(\sum k^2\), \(\sum k^3\), and compare the three worlds (D1–D3): what each of them guarantees and what it does not.

Your answer (exercise D3.6): …

Exercises for independent practice#

The rules are the same as in Lab 1: the exercises are for your own practice, and each of them is a single function with the given name that returns its result. You may use SymPy (import sympy as sp) or plain Python (the modules fractions and math) — only the returned value matters.

Z1. Powers of the golden ratio ★#

Let \(m\) satisfy the equation \(m^2 + m - 1 = 0\) (i.e., \(m = \frac{1}{1+m}\)). For every \(n \ge 0\) there exist uniquely determined integers \(a_n, b_n\) such that \(m^n = a_n + b_n m\) (for both roots \(m\) simultaneously). Write a function potega_m(n) that returns the tuple (a_n, b_n) of integers.

Examples: potega_m(0) == (1, 0), potega_m(2) == (1, -1), potega_m(10) == (34, -55).

Hint: the remainder of \(x^n\) upon division by \(x^2 + x - 1\) (exercise B5), or the recurrence that follows from \(m^{n+1} = m \cdot m^n\).

Z2. Power sums ★★#

Write a function wspolczynniki_sumy_poteg(p) that, for \(p \ge 0\), returns the list of coefficients of the polynomial \(S_p(n) = \sum_{k=1}^{n} k^p\) (in the variable \(n\)), from the coefficient of \(n^{p+1}\) down to the constant term — the list has length \(p + 2\). The coefficients must be exact rational numbers: fractions.Fraction or sympy.Rational (the test prints str() of each element of the list). The function must work for \(p \le 30\).

Examples: for \(p = 1\) we have \(S_1(n) = \frac12 n^2 + \frac12 n\), so [str(c) for c in wspolczynniki_sumy_poteg(1)] == ['1/2', '1/2', '0']; for \(p = 2\) the result is ['1/3', '1/2', '1/6', '0'].

Z3. The last digit of \(A_n\) ★★★#

For \((1 + \sqrt2)^n = A_n + B_n\sqrt2\) (\(A_n, B_n \in \mathbb{Z}\)), write a function ostatnia_cyfra_A(n) that returns the last decimal digit of \(A_n\) for \(0 \le n \le 10^{18}\).

Examples: ostatnia_cyfra_A(3) == 7 (since \((1+\sqrt2)^3 = 7 + 5\sqrt2\)), ostatnia_cyfra_A(1000) == 7.

Hint: for \(n = 10^{18}\), neither expanding the power nor a loop of \(n\) steps will finish in time. Study the sequence \(A_n \bmod 10\) (exercise B2(d)) — and justify your observation — or use fast exponentiation.

def potega_m(n):
    # TWÓJ KOD
    ...

def wspolczynniki_sumy_poteg(p):
    # TWÓJ KOD
    ...

def ostatnia_cyfra_A(n):
    # TWÓJ KOD
    ...

# Testy lokalne — odkomentuj, gdy funkcje będą gotowe:
# assert potega_m(0) == (1, 0) and potega_m(2) == (1, -1) and potega_m(10) == (34, -55)
# assert [str(c) for c in wspolczynniki_sumy_poteg(2)] == ['1/3', '1/2', '1/6', '0']
# assert ostatnia_cyfra_A(3) == 7 and ostatnia_cyfra_A(1000) == 7
# print("Testy przykładowe przechodzą.")

Next: the theme of machine arithmetic from exercise D1 is developed further in the deep dive IEEE 754: floating-point numbers from the inside and in the problem set Lab 3: Floating-point arithmetic — IEEE 754 in practice.