SymPy: Symbolic Mathematics
Hendrik Speleers
SymPy: Symbolic Mathematics
●
Overview
– A symbolic calculator
– Algebraic manipulation
●
Substitution, simplification, factorization, ...
– Calculus
●
Series, limits, differentiation and integration
– Linear algebra
●
Matrix manipulation and decompositions
– Solvers
●
Linear and nonlinear (system of) equations
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
SymPy
– Symbolic Python
– Python extension for symbolic mathematics
●
Performing algebraic manipulations on symbolic expressions
●
Evaluating expressions with arbitrary precision
●
Similar to: Mathematica, Maple
●
Keeping code as simple as possible and easily extensible
– Import convention
import sympy as sym
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
A symbolic calculator
– A simple demo
In [1]: x, y = [Link]('x y')
In [2]: expr = x + 3*y
In [3]: expr
Out[3]: x + 3*y
In [4]: expr + 1
Out[4]: x + 3*y + 1
In [5]: (expr + x)**2
Out[5]: (2*x + 3*y)**2
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
A symbolic calculator
– Symbolic variables need to be explicitly defined as symbols
In [1]: x = [Link]('x')
In [2]: x, y = [Link]('x y')
In [3]: x, y = [Link]('x,y')
In [4]: x, y, z = [Link]('x:z')
– Specific properties can be assigned to symbols
In [5]: k = [Link]('k', integer=True)
In [6]: x, y, z = [Link]('x,y,z', real=True)
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
A symbolic calculator
– Data types
● Symbolic: [Link]
● Numeric: [Link], [Link], [Link]
– Be careful when using integer fractions
In [1]: x = [Link]('x')
In [2]: x + 1/2 # Symbol + Float
Out[2]: x + 0.5
In [3]: x + [Link](1, 2) # Symbol + Rational
Out[3]: x + 1/2
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
A symbolic calculator
– Symbolic constants: [Link], sym.E, sym.I, [Link]
– Symbolic functions:
● Number-theory functions: [Link](n), [Link](n, k)
● Power functions: [Link](x), [Link](x), [Link](x), [Link](x, n)
● Trigonometric functions: [Link](x), [Link](x), [Link](x)
●
Many more...
In [1]: f = 4*[Link]**2
In [2]: [Link](f)
Out[2]: 2*pi
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Basic manipulation
– Substitution
● Single variable: [Link](old, new)
● Multiple variables: [Link](iterable)
In [1]: expr = 1 + x*y
In [2]: [Link](x, [Link])
Out[2]: pi*y + 1
In [3]: [Link]({x:[Link], y:2})
Out[3]: 1 + 2*pi
In [4]: [Link]([(x, y+2), (y, 2)])
Out[4]: 9
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Basic manipulation
– Numerical evaluation
● Arbitrary precision: [Link](n=15, subs=None)
In [1]: expr = [Link](8)
In [2]: expr, [Link]()
Out[2]: (2*sqrt(2), 2.82842712474619)
In [3]: [Link](100)
Out[3]: 3.1415926535897932384626433832795028841...
In [4]: [Link](x).evalf(subs={x:2})
Out[4]: 7.38905609893065
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Basic manipulation
– Numerical evaluation
● Be careful when combining with numpy
In [1]: a = [Link](2).evalf()
In [2]: type(a)
Out[2]: [Link]
In [3]: a_array = [Link]([a, a])
In [4]: [Link](a_array)
--------------------------------------
AttributeError ----> 1 [Link](a_array)
'Float' object has no attribute 'sin'
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Basic manipulation
– Numerical evaluation
● Be careful when combining with numpy
In [1]: a = [Link](2).evalf()
In [2]: a_float = float(a)
In [3]: type(a_float)
Out[3]: float
In [4]: a_array = [Link]([a_float, a_float])
In [5]: [Link](a_array)
Out[5]: array([0.89385495, 0.89385495])
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Algebraic manipulation
– Simplification
● General purpose: [Link](expr) or [Link]()
● Several more specific functions (trigsimp, powsimp, combsimp, ...)
In [1]: expr = [Link](x)**2 + [Link](x)**2
In [2]: [Link]()
Out[2]: 1
In [3]: num = x**3 + x**2 - x - 1
...: denom = x**2 + 2*x + 1
In [4]: [Link](num/denom)
Out[4]: x - 1
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Algebraic manipulation
– Polynomial manipulation
● Expansion: [Link](expr) or [Link]()
● Factorisation: [Link](expr) or [Link]()
● Collect powers: [Link](expr, syms) or [Link](syms)
In [1]: [Link]((x + 2)*(x - 3))
Out[1]: x**2 - x - 6
In [2]: [Link](x**3 - x**2 + x - 1)
Out[2]: (x - 1)*(x**2 + 1)
In [3]: [Link](2*x**2 + x*y + x - z*x**2, x)
Out[3]: x**2*(2 - z) + x*(y + 1)
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Algebraic manipulation
– Trigonometric manipulation
● Simplification: [Link](expr) or [Link]()
● Expansion: sym.expand_trig(expr)
In [1]: [Link]([Link](x)/[Link](x))
Out[1]: sin(2*x)/2
In [2]: [Link]([Link](x)/[Link](x))
Out[2]: cosh(x)
In [3]: sym.expand_trig([Link](x + y))
Out[3]: sin(x)*cos(y) + sin(y)*cos(x)
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Calculus
– Sums and products
● Syntax: [Link](expr, *args), [Link](expr, *args)
● The range represented by tuples (index, a, b) is collected in *args
In [1]: [Link](1/(2**k), (k, 0, [Link]))
Out[1]: 2
In [2]: [Link]((k+1)*(x+k), (k, 0, 4))
Out[2]: 15*x + 40
In [3]: [Link](2*k+x, (k, 0, 4))
Out[3]: x*(x + 2)*(x + 4)*(x + 6)*(x + 8)
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Calculus
– Taylor series
● Syntax: [Link](expr, *args) or [Link](*args)
● The variable, expansion point and order are collected in *args
In [1]: expr = [Link](x)
In [2]: [Link]()
Out[2]: 1 - x**2/2 + x**4/24 + O(x**6)
In [3]: [Link](x, x0=[Link]/2, n=3)
Out[3]: pi/2 - x + O((x - pi/2)**3, (x, pi/2))
In [4]: taylor_sin = [Link]([Link](x), n=5)
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Calculus
– Limits
● Syntax: [Link](expr, *args) or [Link](*args)
● The variable and limit point are collected in *args
In [1]: expr = x**2/[Link](x)
In [2]: [Link](x, [Link])
Out[2]: nan
In [3]: [Link](x, [Link])
Out[3]: 0
In [4]: lim_sinc = [Link]([Link](x)/x, x, 0)
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Calculus
– Differentiation
● Syntax: [Link](expr, *args) or [Link](*args)
● Variables and/or the derivative order are collected in *args
In [1]: [Link](x).diff()
Out[1]: cos(x)
In [2]: [Link]([Link](x), x, 3)
Out[2]: -cos(x)
In [3]: [Link]([Link](x*y), x, 2, y, 1)
Out[3]: -y*(x*y*cos(x*y) + 2*sin(x*y))
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Calculus
– Integration
● Syntax: [Link](expr, *args) or [Link](*args)
● Indefinite: variables are collected in *args
● Definite: tuples (var, a, b) are collected in *args
In [1]: [Link](x).integrate()
Out[1]: sin(x)
In [2]: [Link]([Link](x), x)
Out[2]: sin(x)
In [3]: [Link]([Link](-x), (x, 0, [Link]))
Out[3]: 1
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Calculus
– Numerical evaluation
● For integrals/sums/products: combine evalf with [Link]/[Link]/[Link]
●
Can be useful when symbolic computation is very hard
In [1]: expr = [Link]([Link](x))
In [2]: [Link](expr, (x, 0, 4))
Out[2]: Integral(exp(sin(x)), (x, 0, 4))
In [3]: [Link](expr, (x, 0, 4)).evalf()
Out[3]: 6.79647242142120
In [4]: [Link](1/k**2, (k, 1, [Link])).evalf()
Out[4]: 1.64493406684823
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Linear algebra
– Matrix data type
– Matrix creation via [Link]
●
List of lists, flattened list, or function as input
In [1]: M1 = [Link]([[0, 1, 2], [3, 4, 5]])
In [2]: M2 = [Link](2, 3, [0, 1, 2, 3, 4, 5])
In [3]: def f(i,j): return 3*i+j
In [4]: M3 = [Link](2, 3, f)
In [5]: M3
Out[5]: Matrix([[0, 1, 2],
...: [3, 4, 5]])
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Linear algebra
– Special matrices
● Common: [Link](rows, cols=None), [Link](...), [Link](...)
● Diagonal: [Link](*values)
In [1]: A = [Link](2)
In [2]: B = [Link](2, 3)
In [3]: C = [Link](3, B, 2)
In [4]: C
Out[4]: Matrix([[3, 0, 0, 0, 0],
...: [0, 1, 1, 1, 0],
...: [0, 1, 1, 1, 0],
...: [0, 0, 0, 0, 2]])
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Linear algebra
– Matrix manipulation
●
Indexing and slicing (pass by value)
In [1]: M = [Link]([[0, 1, 2], [3, 4, 5]])
In [2]: M[1, 2] = x
In [3]: M[-1, :]
Out[3]: Matrix([[3, 4, x]])
In [4]: M2 = M[:, :]
In [5]: M2[0, 0] = 100
In [6]: M[0, 0] == 100
Out[6]: False
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Linear algebra
– Matrix manipulation
● Access: [Link](i), [Link](i)
● Deletion (in-place): M.row_del(i), M.col_del(i)
● Insertion (copy): M.row_insert(i, matrix), M.col_insert(i, matrix)
In [7]: [Link](1)
Out[7]: Matrix([[3, 4, x]])
In [8]: M.row_insert(0, [Link]([[1, -2, 3]]))
Out[8]: Matrix([[1, -2, 3],
...: [0, 1, 2],
...: [3, 4, x]])
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Linear algebra
– Matrix operations
● Basic arithmetic operations (+, -, *, ** )
In [1]: M = [Link]([[-1, 1], [2, x]])
In [2]: b = [Link]([4, 5])
In [3]: M * b Be careful: this are
Out[3]: Matrix([[ 1], linear algebra operations:
...: [5*x + 8]])
* and ** not elementwise!
In [4]: M**2
Out[4]: Matrix([[ 3, x - 1],
...: [2*x - 2, x**2 + 2]])
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Linear algebra
– Matrix operations
● Transpose: M.T
● Determinant: [Link]()
● Inverse: [Link]()
● Nullspace: [Link]()
● Columnspace: [Link]()
● Eigenvalues: [Link](), [Link]()
In [5]: [Link]()
Out[5]: -x - 2
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Linear algebra
– Matrix decompositions
● Diag: P, D = [Link]()
● LU: L, U, perm = [Link]()
● Cholesky: C = [Link]()
● QR: Q, R = [Link]()
– And solvers of M * x = b based on decompositions
● Diag: x = M.diagonal_solve(b)
● LU: x = [Link](b)
● Cholesky: x = M.cholesky_solve(b)
● QR: x = [Link](b)
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Linear algebra
– Example
In [1]: M = [Link]([[-1, 0], [2, x]])
...: B = [Link]([[x+1, 3], [5, 1]])
In [2]: [Link]() * B
Out[2]: Matrix([[ -x - 1, -3],
...: [2*(x + 1)/x + 5/x, 7/x]])
In [3]: [Link](B)
Out[3]: Matrix([[ -x - 1, -3],
...: [(2*x + 7)/x, 7/x]])
In [4]: [Link](Out[2]-Out[3]).is_zero
Out[4]: True
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Solvers
– Univariate equation
● general: [Link](equation, symbol=None)
● polynomial: [Link](equation, symbol=None)
●
Equation assumed to equal zero
In [1]: [Link](x**3 - 6*x**2 + 9*x, x)
Out[1]: {0, 3}
In [2]: [Link](x**3 - 6*x**2 + 9*x, x)
Out[2]: {0: 1, 3: 2}
In [3]: [Link]([Link](x) - 1, x)
Out[3]: ImageSet(Lambda(_n, 2*_n*I*pi), [Link])
Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Solvers
– System of equations
● System of linear eqns.: [Link](eqns, *symbols)
● System of nonlinear eqns.: [Link](eqns, *symbols)
●
Equations assumed to equal zero
In [1]: eqns = [x + y + z - 1, x + y + 2*z - 3]
In [2]: [Link](eqns, x, y, z)
Out[2]: {(-y - 1, y, 2)}
In [3]: [Link](eqns, y, z)
Out[3]: {(-x - 1, 2)}
In [4]: [Link]([x*y - 1, x - 2], x, y)
Out[4]: {(2, 1/2)} Lab Calc
2023-2024
SymPy: Symbolic Mathematics
●
Pretty printing
– Default printing is often string-based
In [1]: [Link]([Link](1/x), x)
Out[1]: Integral(sqrt(1/x), x)
– Pretty printing can be activated
In [1]: sym.init_printing(pretty_print=True)
In [2]: [Link]([Link](1/x), x)
Out[2]:
Lab Calc
2023-2024