2.4. SymPY#
last update: Feb 07, 2024
SymPy is a Python library for symbolic mathematics. - sympy doc
In this page, you see examples of sympy usage.
from sympy import *
2.4.1. Declare symbols#
x = Symbol("x")
y = Symbol("y")
(x + y) ** 2
\[\displaystyle \left(x + y\right)^{2}\]
2.4.2. Expansion#
f = expand((x + y) ** 2)
display(f)
\[\displaystyle x^{2} + 2 x y + y^{2}\]
2.4.3. Substitution#
f.subs({x: 1, y: 2})
\[\displaystyle 9\]
2.4.4. Factorization#
factor(x**2 - 4 * x + 3)
\[\displaystyle \left(x - 3\right) \left(x - 1\right)\]
2.4.5. Solve equations#
solve(x**2 - x - 1)
[1/2 - sqrt(5)/2, 1/2 + sqrt(5)/2]
2.4.6. Partial fraction decomposition#
apart(1 / (x**5 - 1))
\[\displaystyle - \frac{x^{3} + 2 x^{2} + 3 x + 4}{5 \left(x^{4} + x^{3} + x^{2} + x + 1\right)} + \frac{1}{5 \left(x - 1\right)}\]
2.4.7. Integrals and derivatives#
a = Symbol("a") # Without real=True, a is treated as a complex number.
b = Symbol("b")
u = exp(a * x) * sin(b * x)
display(u)
\[\displaystyle e^{a x} \sin{\left(b x \right)}\]
int_u = integrate(u, x)
display(int_u)
\[\begin{split}\displaystyle \begin{cases} 0 & \text{for}\: a = 0 \wedge b = 0 \\\frac{x e^{- i b x} \sin{\left(b x \right)}}{2} - \frac{i x e^{- i b x} \cos{\left(b x \right)}}{2} - \frac{e^{- i b x} \cos{\left(b x \right)}}{2 b} & \text{for}\: a = - i b \\\frac{x e^{i b x} \sin{\left(b x \right)}}{2} + \frac{i x e^{i b x} \cos{\left(b x \right)}}{2} - \frac{e^{i b x} \cos{\left(b x \right)}}{2 b} & \text{for}\: a = i b \\\frac{a e^{a x} \sin{\left(b x \right)}}{a^{2} + b^{2}} - \frac{b e^{a x} \cos{\left(b x \right)}}{a^{2} + b^{2}} & \text{otherwise} \end{cases}\end{split}\]
R = diff(u, x, 2) + u + x
display(R)
\[\displaystyle x + \left(a^{2} \sin{\left(b x \right)} + 2 a b \cos{\left(b x \right)} - b^{2} \sin{\left(b x \right)}\right) e^{a x} + e^{a x} \sin{\left(b x \right)}\]
2.4.8. Summation#
k, N = symbols("k, N", integer=True)
factor(summation(k, (k, 1, N)))
\[\displaystyle \frac{N \left(N + 1\right)}{2}\]
2.4.9. Limits#
\[ \lim_{x \to 0} \frac{\sin x}{x} = 1 \]
limit(sin(x) / x, x, 0)
\[\displaystyle 1\]
2.4.10. Other Examples#
s = Symbol("s")
t = Symbol("t")
l = (s**2 * x**3) + (t * x**2) + (3 * x) + 1
display(l)
\[\displaystyle s^{2} x^{3} + t x^{2} + 3 x + 1\]
int_l = integrate(l, (x, 0, 1))
display(int_l)
\[\displaystyle \frac{s^{2}}{4} + \frac{t}{3} + \frac{5}{2}\]