Symbolic Algebra with `sympy`
====


```python
from sympy import *
```


```python
from sympy import init_session
init_session()
```

    IPython console for SymPy 1.5.1 (Python 3.6.10-64-bit) (ground types: gmpy)
    
    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 https://docs.sympy.org/1.5.1/
    


Basics
----


```python
from sympy.stats import *
E(Die('X', 6))
```


```python
sqrt(8)
```


```python
expr = x + 2*y
```


```python
expr2 = x*expr
```


```python
expr2
```


```python
expand(expr2)
```


```python
factor(expand(expr2))
```


```python
diff(sin(x) * exp(x), x)
```


```python
integrate(exp(x)*sin(x) + exp(x)*cos(x), x)
```


```python
integrate(sin(x**2), (x, -oo, oo))
```


```python
dsolve(Eq(f(t).diff(t, t) - f(t), exp(t)), f(t))
```


```python
Matrix([[1,2],[2,2]]).eigenvals()
```


```python
nu = symbols('nu')
besselj(nu, z).rewrite(jn)
```


```python
latex(Integral(cos(x)**2, (x, 0, pi)))
```




    '\\int\\limits_{0}^{\\pi} \\cos^{2}{\\left(x \\right)}\\, dx'




```python
expr = cos(x) + 1
```


```python
expr.subs(x, y)
```


```python
expr = x**y
expr = expr.subs(y, x**y)
expr = expr.subs(y, x**y)
expr = expr.subs(x, x**x)
```


```python
expr
```


```python
expr = sin(2*x) + cos(2*x)
expand_trig(expr)
```


```python
expr.subs(sin(2*x), 2*sin(x)*cos(x))
```


```python
expr = x**4 - 4*x**3 + 4*x**2 - 2*x +3
```


```python
replacements = [(x**i, y**i) for i in range(5) if i%2 == 0]
expr.subs(replacements)
```


```python
sexpr = "x**4 - 4*x**3 + 4*x**2 - 2*x +3"
sympify(sexpr)
```


```python
sqrt(8).evalf()
```


```python
pi.evalf(100)
```


```python
expr = cos(2*x)
expr.evalf(subs = {x: 2.4})
```


```python
expr = cos(x)**2 + sin(x)**2
expr.evalf(subs = {x: 1}, chop=True)
```


```python
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
----


```python
simplify(sin(x)**2 + cos(x)**2)
```


```python
simplify(gamma(x) / gamma(x-2))
```


```python
expand((x + y)**3)
```


```python
factor(x**3 - x**2 + x - 1)
```


```python
factor_list(x**3 - x**2 + x - 1)
```


```python
expand((cos(x) + sin(x))**2)
```


```python
expr = x*y + x - 3 + 2*x**2 - z*x**2 + x**3
cexpr = collect(expr, x)
cexpr
```


```python
cexpr.coeff(x**2)
```


```python
cancel((x**2 + 2*x + 1) / (x**2 + x))
```


```python
expr = (x*y**2 - 2*x*y*z + x*z**2 + y**2 - 2*y*z + z**2)/(x**2 - 1)
```


```python
cancel(expr)
```


```python
factor(expr)
```


```python
expr = (4*x**3 + 21*x**2 + 10*x + 12)/(x**4 + 5*x**3 + 5*x**2 + 4*x)
```


```python
apart(expr)
```


```python
trigsimp(sin(x)*tan(x)/sec(x))
```


```python
trigsimp(cosh(x)**2 + sinh(x)**2)
```


```python
expand_trig(sin(x + y))
```


```python
x, y = symbols('x y', positive=True)
a, b = symbols('a b', real=True)
z, t, c = symbols('z t c')
```


```python
powsimp(x**a*x**b)
```


```python
powsimp(x**a*y**a)
```


```python
powsimp(t**c*z**c)
```


```python
powsimp(t**c*z**c, force=True)
```


```python
expand_power_exp(x**(a + b))
```


```python
expand_power_base((x*y)**a)
```


```python
powdenest((x**a)**b)
```


```python
n = symbols('n', real=True)
```


```python
expand_log(log(x*y))
```


```python
expand_log(log(x**n))
```


```python
logcombine(n*log(x))
```


```python
x, y, z = symbols('x y z')
k, m, n = symbols('k m n')
```


```python
factorial(n)
```


```python
binomial(n, k)
```


```python
hyper([1,2], [3], z)
```


```python
factorial(x).rewrite(gamma)
```


```python
tan(x).rewrite(sin)
```


```python
expand_func(gamma(x + 3))
```


```python
hyperexpand(hyper([1, 1], [2], z))
```


```python
expr =  meijerg([[1],[1]], [[1],[]], -z)
```


```python
expr
```


```python
hyperexpand(expr)
```


```python
combsimp(binomial(n+1, k+1)/binomial(n, k))
```


```python
def list_to_frac(l):
    expr = Integer(0)
    for i in reversed(l[1:]):
        expr += i
        expr = 1/expr
    return l[0] + expr
```


```python
list_to_frac([1,2,3,4])
```


```python
syms = symbols('a0:5')
```


```python
syms
```


```python
frac = list_to_frac(syms)
```


```python
frac
```


```python
frac = cancel(frac)
```


```python
frac
```


```python
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
----


```python
diff(cos(x), x)
```


```python
diff(x**4, x, 3)
```


```python
expr = exp(x*y*z)
diff(expr, x, y, 2, z, 4)
```


```python
deriv = Derivative(expr, x, y, 2, z, 4)
deriv
```


```python
deriv.doit()
```


```python
integrate(cos(x), x)
```


```python
integrate(exp(-x), (x, 0, oo))
```


```python
integrate(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
```


```python
integrate(x**x, x)
```


```python
expr = Integral(log(x)**2, x)
expr
```


```python
expr.doit()
```


```python
integrate(sin(x**2), x)
```


```python
integrate(x**y*exp(-x), (x, 0, oo))
```


```python
limit(sin(x)/x, x, 0)
```


```python
expr = Limit((cos(x) - 1)/x, x, 0)
expr
```


```python
expr.doit()
```


```python
limit(1/x, x, 0, '-')
```


```python
expr = exp(sin(x))
expr.series(x, 0, 4)
```


```python
x + x**3 + x**6 + O(x**4)
```


```python
x * O(1)
```


```python
expr.series(x, 0, 4).removeO()
```


```python
exp(x - 6).series(x, 6)
```


```python
exp(x - 6).series(x, 6).removeO().subs(x, x - 6)
```

Working with matrices
----


```python
M = Matrix([[1,2,3],[3,2,1]])
P = Matrix([0,1,1])
M*P
```


```python
M
```


```python
M.shape
```


```python
M.col(-1)
```


```python
M = Matrix([[1,3], [-2,3]])
M**-1
```


```python
M.T
```


```python
eye(3)
```


```python
diag(1,2,3)
```


```python
M.det()
```


```python
M= Matrix([[1,0,1,3],[2,3,4,7],[-1,-3,-3,-4]])
M
```


```python
M.rref()
```


```python
M = Matrix([[1,2,3,0,0],[4,10,0,0,1]])
M
```


```python
M.nullspace()
```


```python
M = Matrix([[1,1,2],[1,4,1],[2,1,5]])
M
```


```python
L, U, P = M.LUdecomposition()
L, U, P
```


```python
L*U
```


```python
L, D = M.LDLdecomposition()
L, D
```


```python
L*D*L.T
```


```python
L = M.cholesky()
L
```


```python
L*L.T
```


```python
M = Matrix([[3, -2, 4, -2], [5,3,-3,-2], [5,-2,2,-2], [5,-2,-3,3]])
M
```


```python
M.eigenvals()
```


```python
M.eigenvects()
```


```python
P, D = M.diagonalize()
```


```python
P
```


```python
D
```


```python
P*D*P**-1
```


```python
lamda = symbols('lamda')
p = M.charpoly(lamda)
p
```


```python
factor(p)
```

Solving Algebraic and Differential Equations
----


```python
solve(x**2 - 1, x)
```


```python
solve((x - y + 2, x + y -3), (x, y))
```


```python
solve(x**3 - 6*x**2 + 9*x, x)
```


```python
roots(x**3 - 6*x**2 + 9*x, x)
```


```python
f, g = symbols('f g', cls=Function)
```


```python
f(x).diff(x)
```


```python
diffeq = Eq(f(x).diff(x, 2) - 2*f(x).diff(x) + f(x), sin(x))
```


```python
diffeq
```


```python
dsolve(diffeq, f(x))
```


```python
dsolve(f(x).diff(x)*(1 - sin(f(x))), f(x))
```


```python
a, t = symbols('a t')
f(t).diff(t)
diffeq = Eq(f(t).diff(t), a*t)
```


```python
diffeq
```


```python
dsolve(diffeq, f(t))
```


```python
x = symbols('x', cls=Function)
diffeq = Eq(x(t).diff(t), a*x(t))
diffeq
```


```python
dsolve(diffeq, x(t))
```

Numerics
----


```python
N(pi, 10)
```


```python
x = symbols('x')
```


```python
expr = Integral(sin(x)/(x**2), (x, 1, oo))
```


```python
expr.evalf()
```


```python
expr.evalf(maxn=20)
```


```python
expr.evalf(quad='osc')
```


```python
expr.evalf(20, quad='osc')
```


```python
expr = Integral(sin(1/x), (x, 0, 1))
expr
```


```python
expr.evalf()
```


```python
expr = expr.transform(x, 1/x)
expr
```


```python
expr.evalf(quad='osc')
```


```python
nsimplify(pi, tolerance=0.001)
```


```python
expr = sin(x)/x
```


```python
%timeit expr.evalf(subs={x: 3.14})
```

    238 µs ± 3.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)



```python
f1 = lambdify(x, expr)
%timeit f1(3.14)
```

    1.36 µs ± 24.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)



```python
f2 = lambdify(x, expr, 'numpy')
%timeit f2(3.14)
```

    1.36 µs ± 22.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)



```python
%timeit f2(np.linspace(1, 10, 10000))
```

    475 µs ± 3.08 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)



```python
%timeit [f1(x) for x in np.linspace(1, 10, 10000)]
```

    20.1 ms ± 212 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)



```python
from mpmath import *
```


```python
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]



```python
from sympy.plotting import plot
%matplotlib inline

plot(x*y**3 - y*x**3)
pass
```


```python
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
----


```python
from sympy.stats import *
```


```python
k = Symbol("k", positive=True)
theta = Symbol("theta", positive=True)
z = Symbol("z")
X = Gamma("x", k, theta)
```


```python
D = density(X)(z)
D
```


```python
C = cdf(X, meijerg=True)(z)
C
```


```python
E(X)
```


```python
V = variance(X)
V
```


```python
simplify(V)
```


```python
N = Normal('Gaussian', 10, 5)
density(N)(z)
```


```python
density(N)(3).evalf()
```


```python
simplify(cdf(N)(z))
```


```python
P(N > 10)
```


```python
sample(N)
```


```python

```

b9ca918c053f2840d80ca5913bcf88db021424ca
ipynb
Jupyter Notebook
notebooks/X01_Symbolic_Algebra.ipynb
Yijia17/sta-663-2021
e6484e3116c041b8c8eaae487eff5f351ff499c9
MIT
2021-01-19T16:35:54.000Z
2022-01-01T02:12:30.000Z
notebooks/X01_Symbolic_Algebra.ipynb
Yijia17/sta-663-2021
e6484e3116c041b8c8eaae487eff5f351ff499c9
MIT
notebooks/X01_Symbolic_Algebra.ipynb
Yijia17/sta-663-2021
e6484e3116c041b8c8eaae487eff5f351ff499c9
MIT
2021-01-19T16:26:13.000Z
2022-03-15T05:10:14.000Z
Qwen/Qwen-72B
1. YES
2. YES