

# SymPy Expressions

SymPy expressions reason about mathematics and generate numeric code.


```
from sympy import *
from sympy.abc import x, y, z
init_printing(use_latex='mathjax')
```

### Operations on SymPy objects create expressions


```
x + y
```




$$x + y$$




```
type(x + y)
```




    sympy.core.add.Add



### These expressions can be somewhat complex


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




$$\sin^{2}{\left (x \right )} + 2 \cos{\left (x \right )}$$



### We generate numeric code from these expressions


```
ccode(expr)  # C
```




    'pow(sin(x), 2) + 2*cos(x)'




```
fcode(expr)  # Fortran
```




    '      sin(x)**2 + 2*cos(x)'




```
jscode(expr) # JavaScript
```




    'Math.pow(Math.sin(x), 2) + 2*Math.cos(x)'




```
latex(expr)  # Even LaTeX
```




    '\\sin^{2}{\\left (x \\right )} + 2 \\cos{\\left (x \\right )}'



### We also reason about expressions


```
expr
```




$$\sin^{2}{\left (x \right )} + 2 \cos{\left (x \right )}$$




```
expr.diff(x)
```




$$2 \sin{\left (x \right )} \cos{\left (x \right )} - 2 \sin{\left (x \right )}$$




```
expr.diff(x).diff(x)
```




$$- 2 \sin^{2}{\left (x \right )} + 2 \cos^{2}{\left (x \right )} - 2 \cos{\left (x \right )}$$



### And then can generate code


```
ccode(expr.diff(x).diff(x))
```




    '-2*pow(sin(x), 2) + 2*pow(cos(x), 2) - 2*cos(x)'



### Combining reasoning and code generation gives us more efficient code


```
expr.diff(x).diff(x)
```




$$- 2 \sin^{2}{\left (x \right )} + 2 \cos^{2}{\left (x \right )} - 2 \cos{\left (x \right )}$$




```
simplify(expr.diff(x).diff(x))
```




$$- 2 \cos{\left (x \right )} + 2 \cos{\left (2 x \right )}$$




```
ccode(simplify(expr.diff(x).diff(x)))  # Faster code
```




    '-2*cos(x) + 2*cos(2*x)'



# Final Thoughts

We combine high-level reasoning with low-level code generation.

Blaze does the same thing, just swap out calculus and trig with relational and linear algebra.

9f58702d6de86f52b4f9e49578339939e1797086
ipynb
Jupyter Notebook
docs/source/_static/notebooks/sympy-expressions.ipynb
quantopian-enterprise/blaze
6b686bed87993494b11676ed25e7b30f18ca2248
BSD-3-Clause
2015-08-20T11:53:30.000Z
2022-03-30T19:42:11.000Z
docs/source/_static/notebooks/sympy-expressions.ipynb
quantopian-enterprise/blaze
6b686bed87993494b11676ed25e7b30f18ca2248
BSD-3-Clause
2015-08-20T06:09:38.000Z
2020-10-21T13:44:57.000Z
docs/source/_static/notebooks/sympy-expressions.ipynb
quantopian-enterprise/blaze
6b686bed87993494b11676ed25e7b30f18ca2248
BSD-3-Clause
2015-08-20T08:42:01.000Z
2022-03-16T08:05:19.000Z
Qwen/Qwen-72B
1. YES
2. YES