{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# First contact with SageMath\n", "\n", "This Jupyter notebook presents some elementary features of [SageMath](https://www.sagemath.org/).\n", "\n", "First we set up the display for LaTeX-typset outputs:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "%display latex" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Starting with numbers...\n", "\n", "SageMath knows about $\\pi$, $e$ and $i$ (well, it's mathematical software, isn't it ?):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "e^(i*pi) + 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*--- It's nice, but I thought SageMath was based on Python: shouldn't the above be written* `e**(i*pi) + 1`, \n", "*given that* `^` *is the bitwise XOR operator in Python?*\n", "\n", "Actually, the input cells are **preparsed** by SageMath before being sent to the Python interpreter. The action of the preparser is revealed by the function `preparse`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "preparse(\"e^(i*pi) + 1\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see that indeed, the character `^` has been changed to `**`.\n", "\n", "Another noticable change is `1` $\\to$ `Integer(1)`. This means that the preparser is turning integers into SageMath integers, which belong to the class `Integer`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "type(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This type of integer is much more sophisticated than a mere Python integer (`int`). In particular, it knows to which mathematical set it belongs. The latter is returned by the function `parent`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "parent(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To have more information than just the symbol of the parent, one can use the `print` function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "print(parent(1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us denote this object by the Python variable `Z`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "Z = parent(1)\n", "Z" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`Z` is endowed with many methods, which can be discovered via the **TAB key**:\n", "```\n", " Z.\n", "```\n", "Once a method has been selected, one can get some **documentation** about it via `?`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "Z.cardinality?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A double question mark leads directly to the **source code** (recall that SageMath is free software!):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "Z.cardinality??" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More documentation is available in the [reference manual](https://doc.sagemath.org/html/en/reference/) as well as in various [tutorials and guides](https://doc.sagemath.org/html/en/)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "Z.cardinality()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other methods:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "Z.is_ring()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "Z.is_field()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "Z.zero(), Z.one() # the ring zero and unit elements" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Expressing $1\\in \\mathbb{Z}$ in SageMath:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "1 in Z" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1 is actually the unit element of the ring $\\mathbb{Z}$:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "1 == Z.one()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that there exits a predefined variable, `ZZ`, for $\\mathbb{Z}$:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "Z is ZZ" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "SageMath integers can be arbitrarily large (up to the limit of the computer memory!):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "m = 2^127 - 1\n", "m" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "m.is_prime()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that one has still access to the Python integers, via `int`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "int(1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(_) # the underscore stands for the latest output" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An alternative for accessing Python integers is to use the suffix `r` (standing for \"raw\", i.e. unpreparsed):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "1r" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(_)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The Python integers are automatically converted (coerced) into SageMath integers if necessary, for instance if they are\n", "added to some SageMath integer:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "int(1) + 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(_)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course, SageMath also knows about **rational numbers**:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "2/3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python would have returned 0.6666666666666666. This is not the case here because" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "preparse('2/3')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and the division of the (Sage) integer 2 by the (Sage) integer 3 is the (Sage) rational number $2/3$: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "parent(2/3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "print(_)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As the above examples illustrate, SageMath is based on a **Parent/Element scheme**: `parent(a)` is the algebraic or topological/differential structure to which `a` belongs. \n", "\n", "SageMath has also the concept of **mathematical categories**:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "print(category(Z))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Real numbers\n", "\n", "SageMath can compute numerical values with an arbitrary number of digits:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "n(pi, digits=1000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`n` is the shortcut alias for `numerical_approx`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another interesting computation regards the *Hermite-Ramanujan constant*:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "a = exp(pi*sqrt(163))\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Actually, this number is very close to an integer, as announced by [Charles Hermite in 1859](https://gallica.bnf.fr/ark:/12148/bpt6k6209489m/f60) (probably without using SageMath...):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "n(a, digits=50)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That's clear if we turn off scientific notation:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "n(a, digits=50).str(no_sci=2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Symbolic computations\n", "\n", "Beside numerical computations, SageMath can perform symbolic ones. For instance, it can compute a **derivative**:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f = diff(sin(x^2), x)\n", "f" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Due to the command `%display latex` in the first cell of this notebook, SageMath displays all results, such as the one above, in LaTeX format. To get them in console mode, use the function `print`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The explicit LaTeX code can be obtained:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(latex(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A pdf file with the LaTeX typeset formula is generated by the function `view`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "view(f)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The symbolic variable `x` used above is the only one that is predefined in a SageMath session. All other symbolic variables must be declared explicitly, via the function `var`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "y = var('y')\n", "\n", "alp = var('alp', latex_name=r'\\alpha')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f = alp*y + x\n", "f" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "diff(f, alp)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "SageMath can also compute **primitives**:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "integrate(x^5/(x^3 - 2*x +1), x, hold=True) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "integrate(x^5/(x^3 - 2*x + 1), x) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and of course definite integrals: it suffices to provide the two boundaries after the argument `x`. A first attempt with 0 and 1 fails:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# integrate(x^5/(x^3 - 2*x + 1), x, 0, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Don't panic:** error messages are usually long because they display the whole call stack. The important information lies at the end:\n", "```\n", "ValueError: Integral is divergent\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Choosing the boundaries to be 2 and 3 yields a convergent integral:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "integrate(x^5/(x^3 - 2*x + 1), x, 2, 3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n(_) # numerical approximation of the above result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "SageMath proposes various symbolic engines to evaluate a primitive. The default one is [Maxima](https://maxima.sourceforge.io/):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "integrate(x^5/(x^3 - 2*x + 1), x, algorithm='maxima') # same result as above" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "but [SymPy](https://www.sympy.org) is also available:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "integrate(x^5/(x^3 - 2*x + 1), x, algorithm='sympy')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "as well as [Giac](https://www-fourier.ujf-grenoble.fr/~parisse/giac.html) (for SageMath version >= 10.6, this requires Giac to be installed seperately, cf. https://github.com/sagemath/sagemath-giac): " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "integrate(x^5/(x^3-2*x+1), x, algorithm='giac')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One can even use [WolframAlpha](https://www.wolframalpha.com/calculators/integral-calculator/) via some internet connection:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# integrate(x^5/(x^3-2*x+1), x, algorithm='mathematica_free')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Actually SageMath is endowed with some interface to Mathematica:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cos(x^2)._mathematica_init_()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "as well as to SymPy, Maxima and Giac:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cos(x^2)._sympy_()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(cos(x^2)._maxima_())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# cos(x^2)._giac_() # requires Giac to be installed " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us check the primitive computation:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f = integrate(x^5/(x^3-2*x+1), x) \n", "f" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "diff(f, x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "_.simplify_full()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indefinite integrals can also be computed:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "integrate(exp(-x^2), x, -oo, +oo)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Other examples of symbolic computations: \n", "\n", "- Taylor expansions:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "exp(x).taylor(x, 0, 8)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- limits:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lim(sin(x)/x, x=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- series: Riemann zeta function $\\zeta(s)$ for $s=2$ and $s=3$ (Apéry's constant):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n = var('n') # declaring n as a symbolic variable\n", "sum(1/n^2, n, 1, +oo, hold=True) == sum(1/n^2, n, 1, +oo)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sum(1/n^3, n, 1, +oo)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "numerical_approx(_)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course, as many standard functions, Riemann zeta function is already implemented in SageMath:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "zeta(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Solving an equation:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "solve(x^2 == x + 1, x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Solving a differential equation:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "y = function('y')\n", "eq = diff(y(x), x) - y(x) == x*y(x)^4\n", "eq" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "desolve(eq, y(x))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The power of Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, to illustrate the advantage of being built atop of Python, here is a loop for displaying Pascal's triangle with only two instruction lines:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "for n in range(10): \n", " print([binomial(n, p) for p in range(n+1)])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Next step:\n", "\n", "### Plots and functions in SageMath" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot(sin(x^2), (x, 0, 4), axes_labels=['$x$', '$y$'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And since we are just 4 days after the Revelation, here is a plot of **Riemann zeta function** in the complex plane (brightness = modulus, hue = argument):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "complex_plot(zeta, (-30, 30), (-30, 30))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Zoom around two zeros with real part equal to $\\frac{1}{2}$:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "complex_plot(zeta, (-1, 2), (12, 24))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "See the [dedicated notebook](https://nbviewer.org/github/egourgoulhon/SageMathTour/blob/master/Notebooks/plot_tour_2D.ipynb) for more on plots in SageMath. " ] } ], "metadata": { "kernelspec": { "display_name": "SageMath 10.10", "language": "sage", "name": "sagemath" }, "language": "python", "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.18" } }, "nbformat": 4, "nbformat_minor": 4 }