# SymPy Tutorial

*Arthur Ryman* <br/>
*Last Updated: 2020-04-13*


This notebook contains the examples from the 
[SymPy Tutorial](https://docs.sympy.org/latest/tutorial/index.html).

## Preliminaries

### Installation

The following example confirms that SymPy is installed correctly.


```python
from sympy import *
x = symbols('x')
a = Integral(cos(x)*exp(x), x)
Eq(a, a.doit())
```




$\displaystyle \int e^{x} \cos{\left(x \right)}\, dx = \frac{e^{x} \sin{\left(x \right)}}{2} + \frac{e^{x} \cos{\left(x \right)}}{2}$



The above example shows that SymPy is very nicely integrated with Jupyter. 
The expression is printed as a properly typeset mathematical equation.
I assume that Jupyter sets the default pretty printer to LaTeX.

## Introduction

### What is Symbolic Computation?


```python
import math
math.sqrt(9)
```




    3.0




```python
math.sqrt(8)
```




    2.8284271247461903




```python
import sympy
sympy.sqrt(3)
```




$\displaystyle \sqrt{3}$




```python
sympy.sqrt(8)
```




$\displaystyle 2 \sqrt{2}$




```python
from sympy import symbols
x, y = symbols('x y')
expr = x + 2*y
expr
```




$\displaystyle x + 2 y$




```python
expr + 1
```




$\displaystyle x + 2 y + 1$




```python
expr - x
```




$\displaystyle 2 y$




```python
x*expr
```




$\displaystyle x \left(x + 2 y\right)$




```python
from sympy import expand, factor
expanded_expr = expand(x*expr)
expanded_expr
```




$\displaystyle x^{2} + 2 x y$




```python
factor(expanded_expr)
```




$\displaystyle x \left(x + 2 y\right)$



### The Power of Symbolic Computation


```python
from sympy import *
x, t, z, nu = symbols('x t z nu')
```


```python
init_printing(use_unicode=True)
```


```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
limit(sin(x)/x, x, 0)
```


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


```python
y = Function('y')
dsolve(Eq(y(t).diff(t, t) - y(t), exp(t)), y(t))
```


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


```python
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
Integral(cos(x)**2, (x, 0, pi))
```


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

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


### Why SymPy?

## Gotchas

### Symbols


```python
from sympy import *
```


```python
x + 1
```


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


```python
x, y, z = symbols('x y z')
```


```python
a, b = symbols('b a')
a
```


```python
b
```


```python
crazy = symbols('unrelated')
crazy + 1
```


```python
print(latex(crazy))
```

    unrelated



```python
x = symbols('x')
expr = x + 1
x = 2
print(expr)
```

    x + 1



```python
x = 'abc'
expr = x + 'def'
expr
```




    'abcdef'




```python
x = 'ABC'
expr
```




    'abcdef'




```python
x = symbols('x')
expr = x + 1
expr.subs(x, 2)
```

### Equal signs


```python
x + 1 == 4
```




    False




```python
Eq(x + 1, 4)
```


```python
(x + 1)**2 == x**2 + 2*x + 1
```




    False




```python
a = (x + 1)**2
b = x**2 + 2*x + 1
simplify(a - b)
```


```python
c = x**2 - 2*x + 1
simplify(a - c)
```


```python
a = cos(x)**2 - sin(x)**2
b = cos(2*x)
a.equals(b)
```




    True




```python
simplify(a - b)
```

### Two Final Notes: ^ and /


```python
True ^ False
```




    True




```python
True ^ True
```




    False




```python
Xor(x, y)
```


```python
type(Integer(1) + 1)
```




    sympy.core.numbers.Integer




```python
type(1 + 1)
```




    int




```python
Integer(1)/Integer(3)
```


```python
type(Integer(1)/Integer(3))
```




    sympy.core.numbers.Rational




```python
1/3
```


```python
from __future__ import division
1/2
```


```python
1//2
```


```python
Rational(1, 2)
```


```python
x + 1/2
```


```python
x + Rational(1,2)
```

 ### Further Reading

## Basic Operations


```python
from sympy import *
x, y, z = symbols('x y z')
```

 ### Substitution


```python
expr = cos(x) + 1
expr.subs(x, y)
```


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


```python
expr = x**y
expr
```


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


```python
expr = expr.subs(y, x**x)
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 = cos(x)
expr.subs(x, 0)
```


```python
expr
```


```python
x
```


```python
expr = x**3 + 4*x*y -z
expr.subs([(x, 2), (y, 4), (z, 0)])
```


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

### Converting Strings to SymPy Expression


```python
str_expr = 'x**2 + 3*x - 1/2'
expr = sympify(str_expr)
expr
```


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

### evalf


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


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


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


```python
one = cos(1)**2 + sin(1)**2
(one -1).evalf()
```


```python
(one -1).evalf(chop=True)
```

### lambdify


```python
import numpy
a = numpy.arange(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])




```python
f = lambdify(x, expr, 'math')
f(0.1)
```


```python
def mysin(x):
    """
    My sine. Note that this is only accurate for small x.
    """
    return x
f = lambdify(x, expr, {'sin': mysin})
f(0.1)
```

## Printing

### Printers

### Setting up Pretty Printing


```python
from sympy import init_printing
init_printing()
```


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

    IPython console for SymPy 1.5.1 (Python 3.7.6-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 https://docs.sympy.org/1.5.1/
    



```python
from sympy import *
x, y, z = symbols('x y z')
init_printing()
```


```python
Integral(sqrt(1/x), x)
```

### Printing Functions

#### str


```python
from sympy import *
x, y, z = symbols('x y z')
str(Integral(sqrt(1/x), x))
```




    'Integral(sqrt(1/x), x)'




```python
print(Integral(sqrt(1/x), x))
```

    Integral(sqrt(1/x), x)


#### srepr


```python
srepr(Integral(sqrt(1/x), x))
```




    "Integral(Pow(Pow(Symbol('x'), Integer(-1)), Rational(1, 2)), Tuple(Symbol('x')))"



#### ASCII Pretty Printer


```python
pprint(Integral(sqrt(1/x), x), use_unicode=False)
```

      /          
     |           
     |     ___   
     |    / 1    
     |   /  -  dx
     | \/   x    
     |           
    /            



```python
pretty(Integral(sqrt(1/x), x), use_unicode=False)
```




    '  /          \n |           \n |     ___   \n |    / 1    \n |   /  -  dx\n | \\/   x    \n |           \n/            '




```python
print(pretty(Integral(sqrt(1/x), x), use_unicode=False))
```

      /          
     |           
     |     ___   
     |    / 1    
     |   /  -  dx
     | \/   x    
     |           
    /            


#### Unicode Pretty Printer


```python
pprint(Integral(sqrt(1/x), x), use_unicode=True)
```

    ⌠           
    ⎮     ___   
    ⎮    ╱ 1    
    ⎮   ╱  ─  dx
    ⎮ ╲╱   x    
    ⌡           


#### Latex


```python
print(latex(Integral(sqrt(1/x), x)))
```

    \int \sqrt{\frac{1}{x}}\, dx


#### MathML


```python
from sympy.printing.mathml import print_mathml
print_mathml(Integral(sqrt(1/x), x))
```

    <apply>
    	<int/>
    	<bvar>
    		<ci>x</ci>
    	</bvar>
    	<apply>
    		<root/>
    		<apply>
    			<power/>
    			<ci>x</ci>
    			<cn>-1</cn>
    		</apply>
    	</apply>
    </apply>
    


#### Dot


```python
from sympy.printing.dot import dotprint
from sympy.abc import x
print(dotprint(x+2))
```

    digraph{
    
    # Graph style
    "ordering"="out"
    "rankdir"="TD"
    
    #########
    # Nodes #
    #########
    
    "Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"];
    "Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"];
    "Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"];
    
    #########
    # Edges #
    #########
    
    "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";
    "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";
    }


4e63558f86344165d235a4c0371261f23eae1097
ipynb
Jupyter Notebook
notes/docs.sympy.org/tutorial/tutorial.ipynb
agryman/acmpy
9566a0abce51cb610ec6c79eaea2e2b26b707419
MIT
notes/docs.sympy.org/tutorial/tutorial.ipynb
agryman/acmpy
9566a0abce51cb610ec6c79eaea2e2b26b707419
MIT
2022-01-21T22:17:28.000Z
2022-01-21T22:17:28.000Z
notes/docs.sympy.org/tutorial/tutorial.ipynb
agryman/acmpy
9566a0abce51cb610ec6c79eaea2e2b26b707419
MIT
Qwen/Qwen-72B
1. YES
2. YES