Symbolic Algebra with sympy
¶
from sympy import *
from sympy import init_session
init_session()
IPython console for SymPy 0.7.6.1 (Python 3.5.1-64-bit) (ground types: python)
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
>>> init_printing()
Documentation can be found at http://www.sympy.org
Basics¶
from sympy.stats import *
E(Die('X', 6))
\[\frac{7}{2}\]
sqrt(8)
\[2 \sqrt{2}\]
expr = x + 2*y
expr2 = x*expr
expr2
\[x \left(x + 2 y\right)\]
expand(expr2)
\[x^{2} + 2 x y\]
factor(expand(expr2))
\[x \left(x + 2 y\right)\]
diff(sin(x) * exp(x), x)
\[e^{x} \sin{\left (x \right )} + e^{x} \cos{\left (x \right )}\]
integrate(exp(x)*sin(x) + exp(x)*cos(x), x)
\[e^{x} \sin{\left (x \right )}\]
integrate(sin(x**2), (x, -oo, oo))
\[\frac{\sqrt{2} \sqrt{\pi}}{2}\]
dsolve(Eq(f(t).diff(t, t) - f(t), exp(t)), f(t))
\[f{\left (t \right )} = C_{2} e^{- t} + \left(C_{1} + \frac{t}{2}\right) e^{t}\]
Matrix([[1,2],[2,2]]).eigenvals()
\[\left \{ \frac{3}{2} + \frac{\sqrt{17}}{2} : 1, \quad - \frac{\sqrt{17}}{2} + \frac{3}{2} : 1\right \}\]
nu = symbols('nu')
besselj(nu, z).rewrite(jn)
\[\frac{\sqrt{2} \sqrt{z}}{\sqrt{\pi}} j_{\nu - \frac{1}{2}}\left(z\right)\]
latex(Integral(cos(x)**2, (x, 0, pi)))
'\int_{0}^{\pi} \cos^{2}{\left (x \right )}\, dx'
expr = cos(x) + 1
expr.subs(x, y)
\[\cos{\left (y \right )} + 1\]
expr = x**y
expr = expr.subs(y, x**y)
expr = expr.subs(y, x**y)
expr = expr.subs(x, x**x)
expr
\[\left(x^{x}\right)^{\left(x^{x}\right)^{\left(x^{x}\right)^{y}}}\]
expr = sin(2*x) + cos(2*x)
expand_trig(expr)
\[2 \sin{\left (x \right )} \cos{\left (x \right )} + 2 \cos^{2}{\left (x \right )} - 1\]
expr.subs(sin(2*x), 2*sin(x)*cos(x))
\[2 \sin{\left (x \right )} \cos{\left (x \right )} + \cos{\left (2 x \right )}\]
expr = x**4 - 4*x**3 + 4*x**2 - 2*x +3
replacements = [(x**i, y**i) for i in range(5) if i%2 == 0]
expr.subs(replacements)
\[- 4 x^{3} - 2 x + y^{4} + 4 y^{2} + 3\]
sexpr = "x**4 - 4*x**3 + 4*x**2 - 2*x +3"
sympify(sexpr)
\[x^{4} - 4 x^{3} + 4 x^{2} - 2 x + 3\]
sqrt(8).evalf()
\[2.82842712474619\]
pi.evalf(100)
\[3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068\]
expr = cos(2*x)
expr.evalf(subs = {x: 2.4})
\[0.0874989834394464\]
expr = cos(x)**2 + sin(x)**2
expr.evalf(subs = {x: 1}, chop=True)
\[1.0\]
a = range(10)
expr = sin(x)
f = lambdify(x, expr, "numpy")
f(a)
array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ,
-0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])
Simplify¶
simplify(sin(x)**2 + cos(x)**2)
\[1\]
simplify(gamma(x) / gamma(x-2))
\[\left(x - 2\right) \left(x - 1\right)\]
expand((x + y)**3)
\[x^{3} + 3 x^{2} y + 3 x y^{2} + y^{3}\]
factor(x**3 - x**2 + x - 1)
\[\left(x - 1\right) \left(x^{2} + 1\right)\]
factor_list(x**3 - x**2 + x - 1)
\[\left ( 1, \quad \left [ \left ( x - 1, \quad 1\right ), \quad \left ( x^{2} + 1, \quad 1\right )\right ]\right )\]
expand((cos(x) + sin(x))**2)
\[\sin^{2}{\left (x \right )} + 2 \sin{\left (x \right )} \cos{\left (x \right )} + \cos^{2}{\left (x \right )}\]
expr = x*y + x - 3 + 2*x**2 - z*x**2 + x**3
cexpr = collect(expr, x)
cexpr
\[x^{3} + x^{2} \left(- z + 2\right) + x \left(y + 1\right) - 3\]
cexpr.coeff(x**2)
\[- z + 2\]
cancel((x**2 + 2*x + 1) / (x**2 + x))
\[\frac{1}{x} \left(x + 1\right)\]
expr = (x*y**2 - 2*x*y*z + x*z**2 + y**2 - 2*y*z + z**2)/(x**2 - 1)
cancel(expr)
\[\frac{1}{x - 1} \left(y^{2} - 2 y z + z^{2}\right)\]
factor(expr)
\[\frac{\left(y - z\right)^{2}}{x - 1}\]
expr = (4*x**3 + 21*x**2 + 10*x + 12)/(x**4 + 5*x**3 + 5*x**2 + 4*x)
apart(expr)
\[\frac{2 x - 1}{x^{2} + x + 1} - \frac{1}{x + 4} + \frac{3}{x}\]
trigsimp(sin(x)*tan(x)/sec(x))
\[\sin^{2}{\left (x \right )}\]
trigsimp(cosh(x)**2 + sinh(x)**2)
\[\cosh{\left (2 x \right )}\]
expand_trig(sin(x + y))
\[\sin{\left (x \right )} \cos{\left (y \right )} + \sin{\left (y \right )} \cos{\left (x \right )}\]
x, y = symbols('x y', positive=True)
a, b = symbols('a b', real=True)
z, t, c = symbols('z t c')
powsimp(x**a*x**b)
\[x^{a + b}\]
powsimp(x**a*y**a)
\[\left(x y\right)^{a}\]
powsimp(t**c*z**c)
\[t^{c} z^{c}\]
powsimp(t**c*z**c, force=True)
\[\left(t z\right)^{c}\]
expand_power_exp(x**(a + b))
\[x^{a} x^{b}\]
expand_power_base((x*y)**a)
\[x^{a} y^{a}\]
powdenest((x**a)**b)
\[x^{a b}\]
n = symbols('n', real=True)
expand_log(log(x*y))
\[\log{\left (x \right )} + \log{\left (y \right )}\]
expand_log(log(x**n))
\[n \log{\left (x \right )}\]
logcombine(n*log(x))
\[\log{\left (x^{n} \right )}\]
x, y, z = symbols('x y z')
k, m, n = symbols('k m n')
factorial(n)
\[n!\]
binomial(n, k)
\[{\binom{n}{k}}\]
hyper([1,2], [3], z)
\[\begin{split}{{}_{2}F_{1}\left(\begin{matrix} 1, 2 \\ 3 \end{matrix}\middle| {z} \right)}\end{split}\]
factorial(x).rewrite(gamma)
\[\Gamma{\left(x + 1 \right)}\]
tan(x).rewrite(sin)
\[\frac{2 \sin^{2}{\left (x \right )}}{\sin{\left (2 x \right )}}\]
expand_func(gamma(x + 3))
\[x \left(x + 1\right) \left(x + 2\right) \Gamma{\left(x \right)}\]
hyperexpand(hyper([1, 1], [2], z))
\[- \frac{1}{z} \log{\left (- z + 1 \right )}\]
expr = meijerg([[1],[1]], [[1],[]], -z)
expr
\[\begin{split}{G_{2, 1}^{1, 1}\left(\begin{matrix} 1 & 1 \\1 & \end{matrix} \middle| {- z} \right)}\end{split}\]
hyperexpand(expr)
\[e^{\frac{1}{z}}\]
combsimp(binomial(n+1, k+1)/binomial(n, k))
\[\frac{n + 1}{k + 1}\]
def list_to_frac(l):
expr = Integer(0)
for i in reversed(l[1:]):
expr += i
expr = 1/expr
return l[0] + expr
list_to_frac([1,2,3,4])
\[\frac{43}{30}\]
syms = symbols('a0:5')
syms
\[\left ( a_{0}, \quad a_{1}, \quad a_{2}, \quad a_{3}, \quad a_{4}\right )\]
frac = list_to_frac(syms)
frac
\[a_{0} + \frac{1}{a_{1} + \frac{1}{a_{2} + \frac{1}{a_{3} + \frac{1}{a_{4}}}}}\]
frac = cancel(frac)
frac
\[\frac{a_{0} a_{1} a_{2} a_{3} a_{4} + a_{0} a_{1} a_{2} + a_{0} a_{1} a_{4} + a_{0} a_{3} a_{4} + a_{0} + a_{2} a_{3} a_{4} + a_{2} + a_{4}}{a_{1} a_{2} a_{3} a_{4} + a_{1} a_{2} + a_{1} a_{4} + a_{3} a_{4} + 1}\]
from sympy.printing import print_ccode
print_ccode(frac)
(a0*a1*a2*a3*a4 + a0*a1*a2 + a0*a1*a4 + a0*a3*a4 + a0 + a2*a3*a4 + a2 + a4)/(a1*a2*a3*a4 + a1*a2 + a1*a4 + a3*a4 + 1)
Calculus¶
diff(cos(x), x)
\[- \sin{\left (x \right )}\]
diff(x**4, x, 3)
\[24 x\]
expr = exp(x*y*z)
diff(expr, x, y, 2, z, 4)
\[x^{3} y^{2} \left(x^{3} y^{3} z^{3} + 14 x^{2} y^{2} z^{2} + 52 x y z + 48\right) e^{x y z}\]
deriv = Derivative(expr, x, y, 2, z, 4)
deriv
\[\frac{\partial^{7}}{\partial x\partial y^{2}\partial z^{4}} e^{x y z}\]
deriv.doit()
\[x^{3} y^{2} \left(x^{3} y^{3} z^{3} + 14 x^{2} y^{2} z^{2} + 52 x y z + 48\right) e^{x y z}\]
integrate(cos(x), x)
\[\sin{\left (x \right )}\]
integrate(exp(-x), (x, 0, oo))
\[1\]
integrate(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
\[\pi\]
integrate(x**x, x)
\[\int x^{x}\, dx\]
expr = Integral(log(x)**2, x)
expr
\[\int \log^{2}{\left (x \right )}\, dx\]
expr.doit()
\[x \log^{2}{\left (x \right )} - 2 x \log{\left (x \right )} + 2 x\]
integrate(sin(x**2), x)
\[\frac{3 \sqrt{2} \sqrt{\pi} S\left(\frac{\sqrt{2} x}{\sqrt{\pi}}\right)}{8 \Gamma{\left(\frac{7}{4} \right)}} \Gamma{\left(\frac{3}{4} \right)}\]
integrate(x**y*exp(-x), (x, 0, oo))
\[\begin{split}\begin{cases} \Gamma{\left(y + 1 \right)} & \text{for}\: - \Re{y} < 1 \\\int_{0}^{\infty} x^{y} e^{- x}\, dx & \text{otherwise} \end{cases}\end{split}\]
limit(sin(x)/x, x, 0)
\[1\]
expr = Limit((cos(x) - 1)/x, x, 0)
expr
\[\lim_{x \to 0^+}\left(\frac{1}{x} \left(\cos{\left (x \right )} - 1\right)\right)\]
expr.doit()
\[0\]
limit(1/x, x, 0, '-')
\[-\infty\]
expr = exp(sin(x))
expr.series(x, 0, 4)
\[1 + x + \frac{x^{2}}{2} + \mathcal{O}\left(x^{4}\right)\]
x + x**3 + x**6 + O(x**4)
\[x + x^{3} + \mathcal{O}\left(x^{4}\right)\]
x * O(1)
\[\mathcal{O}\left(x\right)\]
expr.series(x, 0, 4).removeO()
\[\frac{x^{2}}{2} + x + 1\]
exp(x - 6).series(x, 6)
\[-5 + \frac{1}{2} \left(x - 6\right)^{2} + \frac{1}{6} \left(x - 6\right)^{3} + \frac{1}{24} \left(x - 6\right)^{4} + \frac{1}{120} \left(x - 6\right)^{5} + x + \mathcal{O}\left(\left(x - 6\right)^{6}; x\rightarrow6\right)\]
exp(x - 6).series(x, 6).removeO().subs(x, x - 6)
\[x + \frac{1}{120} \left(x - 12\right)^{5} + \frac{1}{24} \left(x - 12\right)^{4} + \frac{1}{6} \left(x - 12\right)^{3} + \frac{1}{2} \left(x - 12\right)^{2} - 11\]
Working with matrices¶
M = Matrix([[1,2,3],[3,2,1]])
P = Matrix([0,1,1])
M*P
\[\begin{split}\left[\begin{matrix}5\\3\end{matrix}\right]\end{split}\]
M
\[\begin{split}\left[\begin{matrix}1 & 2 & 3\\3 & 2 & 1\end{matrix}\right]\end{split}\]
M.shape
\[\left ( 2, \quad 3\right )\]
M.col(-1)
\[\begin{split}\left[\begin{matrix}3\\1\end{matrix}\right]\end{split}\]
M = Matrix([[1,3], [-2,3]])
M**-1
\[\begin{split}\left[\begin{matrix}\frac{1}{3} & - \frac{1}{3}\\\frac{2}{9} & \frac{1}{9}\end{matrix}\right]\end{split}\]
M.T
\[\begin{split}\left[\begin{matrix}1 & -2\\3 & 3\end{matrix}\right]\end{split}\]
eye(3)
\[\begin{split}\left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]\end{split}\]
diag(1,2,3)
\[\begin{split}\left[\begin{matrix}1 & 0 & 0\\0 & 2 & 0\\0 & 0 & 3\end{matrix}\right]\end{split}\]
M.det()
\[9\]
M= Matrix([[1,0,1,3],[2,3,4,7],[-1,-3,-3,-4]])
M
\[\begin{split}\left[\begin{matrix}1 & 0 & 1 & 3\\2 & 3 & 4 & 7\\-1 & -3 & -3 & -4\end{matrix}\right]\end{split}\]
M.rref()
\[\begin{split}\left ( \left[\begin{matrix}1 & 0 & 1 & 3\\0 & 1 & \frac{2}{3} & \frac{1}{3}\\0 & 0 & 0 & 0\end{matrix}\right], \quad \left [ 0, \quad 1\right ]\right )\end{split}\]
M = Matrix([[1,2,3,0,0],[4,10,0,0,1]])
M
\[\begin{split}\left[\begin{matrix}1 & 2 & 3 & 0 & 0\\4 & 10 & 0 & 0 & 1\end{matrix}\right]\end{split}\]
M.nullspace()
\[\begin{split}\left [ \left[\begin{matrix}-15\\6\\1\\0\\0\end{matrix}\right], \quad \left[\begin{matrix}0\\0\\0\\1\\0\end{matrix}\right], \quad \left[\begin{matrix}1\\- \frac{1}{2}\\0\\0\\1\end{matrix}\right]\right ]\end{split}\]
M = Matrix([[3, -2, 4, -2], [5,3,-3,-2], [5,-2,2,-2], [5,-2,-3,3]])
M
\[\begin{split}\left[\begin{matrix}3 & -2 & 4 & -2\\5 & 3 & -3 & -2\\5 & -2 & 2 & -2\\5 & -2 & -3 & 3\end{matrix}\right]\end{split}\]
M.eigenvals()
\[\left \{ -2 : 1, \quad 3 : 1, \quad 5 : 2\right \}\]
M.eigenvects()
\[\begin{split}\left [ \left ( -2, \quad 1, \quad \left [ \left[\begin{matrix}0\\1\\1\\1\end{matrix}\right]\right ]\right ), \quad \left ( 3, \quad 1, \quad \left [ \left[\begin{matrix}1\\1\\1\\1\end{matrix}\right]\right ]\right ), \quad \left ( 5, \quad 2, \quad \left [ \left[\begin{matrix}1\\1\\1\\0\end{matrix}\right], \quad \left[\begin{matrix}0\\-1\\0\\1\end{matrix}\right]\right ]\right )\right ]\end{split}\]
P, D = M.diagonalize()
P
\[\begin{split}\left[\begin{matrix}0 & 1 & 1 & 0\\1 & 1 & 1 & -1\\1 & 1 & 1 & 0\\1 & 1 & 0 & 1\end{matrix}\right]\end{split}\]
D
\[\begin{split}\left[\begin{matrix}-2 & 0 & 0 & 0\\0 & 3 & 0 & 0\\0 & 0 & 5 & 0\\0 & 0 & 0 & 5\end{matrix}\right]\end{split}\]
P*D*P**-1
\[\begin{split}\left[\begin{matrix}3 & -2 & 4 & -2\\5 & 3 & -3 & -2\\5 & -2 & 2 & -2\\5 & -2 & -3 & 3\end{matrix}\right]\end{split}\]
lamda = symbols('lamda')
p = M.charpoly(lamda)
p
\[\operatorname{PurePoly}{\left( \lambda^{4} - 11 \lambda^{3} + 29 \lambda^{2} + 35 \lambda - 150, \lambda, domain=\mathbb{Z} \right)}\]
factor(p)
\[\left(\lambda - 5\right)^{2} \left(\lambda - 3\right) \left(\lambda + 2\right)\]
Solving Algebraic and Differential Equations¶
solve(x**2 - 1, x)
\[\left [ -1, \quad 1\right ]\]
solve((x - y + 2, x + y -3), (x, y))
\[\left \{ x : \frac{1}{2}, \quad y : \frac{5}{2}\right \}\]
solve(x**3 - 6*x**2 + 9*x, x)
\[\left [ 0, \quad 3\right ]\]
roots(x**3 - 6*x**2 + 9*x, x)
\[\left \{ 0 : 1, \quad 3 : 2\right \}\]
f, g = symbols('f g', cls=Function)
f(x).diff(x)
\[\frac{d}{d x} f{\left (x \right )}\]
diffeq = Eq(f(x).diff(x, 2) - 2*f(x).diff(x) + f(x), sin(x))
diffeq
\[f{\left (x \right )} - 2 \frac{d}{d x} f{\left (x \right )} + \frac{d^{2}}{d x^{2}} f{\left (x \right )} = \sin{\left (x \right )}\]
dsolve(diffeq, f(x))
\[f{\left (x \right )} = \left(C_{1} + C_{2} x\right) e^{x} + \frac{1}{2} \cos{\left (x \right )}\]
dsolve(f(x).diff(x)*(1 - sin(f(x))), f(x))
\[f{\left (x \right )} + \cos{\left (f{\left (x \right )} \right )} = C_{1}\]
a, t = symbols('a t')
f(t).diff(t)
diffeq = Eq(f(t).diff(t), a*t)
diffeq
\[\frac{d}{d t} f{\left (t \right )} = a t\]
dsolve(diffeq, f(t))
\[f{\left (t \right )} = C_{1} + \frac{a t^{2}}{2}\]
x = symbols('x', cls=Function)
diffeq = Eq(x(t).diff(t), a*x(t))
diffeq
\[\frac{d}{d t} x{\left (t \right )} = a x{\left (t \right )}\]
dsolve(diffeq, x(t))
\[x{\left (t \right )} = C_{1} e^{a t}\]
Numerics¶
N(pi, 10)
\[3.141592654\]
x = symbols('x')
expr = Integral(sin(x)/(x**2), (x, 1, oo))
expr.evalf()
\[0.5\]
expr.evalf(maxn=20)
\[0.5\]
expr.evalf(quad='osc')
\[0.504067061906928\]
expr.evalf(20, quad='osc')
\[0.50406706190692837199\]
expr = Integral(sin(1/x), (x, 0, 1))
expr
\[\int_{0}^{1} \sin{\left (\frac{1}{x} \right )}\, dx\]
expr.evalf()
\[0.5\]
expr = expr.transform(x, 1/x)
expr
\[\int_{1}^{\infty} \frac{1}{x^{2}} \sin{\left (x \right )}\, dx\]
expr.evalf(quad='osc')
\[0.504067061906928\]
nsimplify(pi, tolerance=0.001)
\[\frac{355}{113}\]
expr = sin(x)/x
%timeit expr.evalf(subs={x: 3.14})
1000 loops, best of 3: 397 µs per loop
f1 = lambdify(x, expr)
%timeit f1(3.14)
The slowest run took 13.44 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 308 ns per loop
f2 = lambdify(x, expr, 'numpy')
%timeit f2(3.14)
The slowest run took 16.41 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 2.2 µs per loop
%timeit f2(np.linspace(1, 10, 10000))
1000 loops, best of 3: 306 µs per loop
%timeit [f1(x) for x in np.linspace(1, 10, 10000)]
100 loops, best of 3: 5.19 ms per loop
from mpmath import *
f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0])
for x in [0, 1, 2.5, 10]:
nprint(f(x), 15)
nprint([cos(x), sin(x)], 15)
[1.0, 0.0]
[1.0, 0.0]
[0.54030230586814, 0.841470984807897]
[0.54030230586814, 0.841470984807897]
[-0.801143615546934, 0.598472144103957]
[-0.801143615546934, 0.598472144103957]
[-0.839071529076452, -0.54402111088937]
[-0.839071529076452, -0.54402111088937]
from sympy.plotting import plot
%matplotlib inline
plot(x*y**3 - y*x**3)
pass
from sympy.plotting import plot3d_parametric_surface
from sympy import sin, cos
u, v = symbols('u v')
plot3d_parametric_surface(cos(u + v), sin(u - v), u-v, (u, -5, 5), (v, -5, 5))
pass
Statistics¶
from sympy.stats import *
k = Symbol("k", positive=True)
theta = Symbol("theta", positive=True)
z = Symbol("z")
X = Gamma("x", k, theta)
D = density(X)(z)
D
\[\frac{z^{k - 1} e^{- \frac{z}{\theta}}}{\theta^{k} \Gamma{\left(k \right)}}\]
C = cdf(X, meijerg=True)(z)
C
\[\begin{split}\begin{cases} - \frac{k \gamma\left(k, 0\right)}{\Gamma{\left(k + 1 \right)}} + \frac{k \gamma\left(k, \frac{z}{\theta}\right)}{\Gamma{\left(k + 1 \right)}} & \text{for}\: z \geq 0 \\0 & \text{otherwise} \end{cases}\end{split}\]
E(X)
\[\frac{\theta}{\Gamma{\left(k \right)}} \Gamma{\left(k + 1 \right)}\]
V = variance(X)
V
\[\frac{\theta^{3} \theta^{k - 1}}{\theta^{k} \Gamma^{2}{\left(k \right)}} \Gamma^{2}{\left(k + 1 \right)} - \frac{2 \theta^{2}}{\Gamma^{2}{\left(k \right)}} \Gamma^{2}{\left(k + 1 \right)} + \frac{\theta \theta^{k + 1}}{\theta^{k} \Gamma{\left(k \right)}} \Gamma{\left(k + 2 \right)}\]
simplify(V)
\[k \theta^{2}\]
N = Normal('Gaussian', 10, 5)
density(N)(z)
\[\frac{\sqrt{2}}{10 \sqrt{\pi}} e^{- \frac{1}{50} \left(z - 10\right)^{2}}\]
density(N)(3).evalf()
\[0.029945493127149\]
simplify(cdf(N)(z))
\[\frac{1}{2} \operatorname{erf}{\left (\frac{\sqrt{2}}{10} \left(z - 10\right) \right )} + \frac{1}{2}\]
P(N > 10)
\[\frac{1}{2}\]
sample(N)
\[6.30254802079348\]