Cheat sheet: Python, SymPy, SageMath

Cheat sheet: Python, SymPy, SageMath#

This page collects the commands used most often in the lectures and labs. Annotated examples and explanations of what happens “under the hood” can be found in the chapters Python for mathematicians: first steps and How does a computer algebra system work?.

Python#

Task

Code

power, integer quotient, remainder

2**10, 17 // 5, 17 % 5, divmod(17, 5)

exact fractions

from fractions import Fraction; Fraction(1, 3) + Fraction(1, 6)

GCD, LCM, integer square root \(\lfloor\sqrt{n}\rfloor\)

math.gcd(a, b), math.lcm(a, b), math.isqrt(n)

binomial coefficient, factorial

math.comb(n, k), math.factorial(n)

comparing float numbers

math.isclose(a, b, rel_tol=1e-12)

list comprehension

[n**2 for n in range(1, 11) if n % 2]

quantifiers

all(...), any(...)

sum, product

sum(...), math.prod(...)

Cartesian product, combinations

itertools.product(A, B), itertools.combinations(A, k)

memoization (caching results)

@functools.lru_cache(maxsize=None)

Warning

In Python, ^ is XOR, not exponentiation. 0.1 + 0.2 != 0.3. round(2.5) == 2, because Python rounds halves to the nearest even integer.

SymPy#

import sympy as sp
x, y = sp.symbols('x y')                 # symbole
n = sp.symbols('n', integer=True, positive=True)   # symbol z założeniami

Task

Code

rational number, square root

sp.Rational(1, 3), sp.sqrt(2)

approximation to a given precision

sp.N(sp.pi, 50), expr.evalf(30)

expansion, factorization

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

rational functions

sp.cancel(e), sp.together(e), sp.apart(e, x)

simplification

sp.simplify(e), sp.trigsimp(e), sp.powsimp(e)

substitution

e.subs(x, 2), e.subs({x: 1, y: 2})

equations

sp.solve(x**2 - 2, x), sp.solveset(e, x, sp.S.Reals)

sum, limit, derivative, integral

sp.summation(k, (k, 1, n)), sp.limit(e, x, 0), sp.diff(e, x), sp.integrate(e, (x, 0, 1))

recurrences

sp.rsolve(eq, f(n), {f(0): 0, f(1): 1})

expression tree

sp.srepr(e), e.func, e.args

numerical function

f = sp.lambdify(x, e, 'numpy')

plot

sp.plot(e, (x, -2, 2))

SageMath (for comparison)#

Task

SageMath

power, fraction

2^10, 1/3 + 1/6 (exact result 1/2)

symbolic variable

x = var('x') (in Sage, the symbol x is predefined)

polynomial ring

R.<x> = QQ[], R.<x> = GF(7)[]

factorization

factor(x^4 - 1), factor(2^32 + 1)

number field

K.<a> = NumberField(x^2 - 2)

matrix

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

range

[1..10], srange(0, 1, 1/4)

approximation

n(pi, digits=50), pi.n(100) (100 bits of precision, about 30 digits)