SymPy Expressions

SymPy expressions reason about mathematics and generate numeric code.


In [1]:
from sympy import *
from sympy.abc import x, y, z
init_printing(use_latex='mathjax')

Operations on SymPy objects create expressions


In [2]:
x + y


Out[2]:
$$x + y$$

In [3]:
type(x + y)


Out[3]:
sympy.core.add.Add

These expressions can be somewhat complex


In [4]:
expr = sin(x)**2 + 2*cos(x)
expr


Out[4]:
$$\sin^{2}{\left (x \right )} + 2 \cos{\left (x \right )}$$

We generate numeric code from these expressions


In [5]:
ccode(expr)  # C


Out[5]:
'pow(sin(x), 2) + 2*cos(x)'

In [6]:
fcode(expr)  # Fortran


Out[6]:
'      sin(x)**2 + 2*cos(x)'

In [7]:
jscode(expr) # JavaScript


Out[7]:
'Math.pow(Math.sin(x), 2) + 2*Math.cos(x)'

In [8]:
latex(expr)  # Even LaTeX


Out[8]:
'\\sin^{2}{\\left (x \\right )} + 2 \\cos{\\left (x \\right )}'

We also reason about expressions


In [9]:
expr


Out[9]:
$$\sin^{2}{\left (x \right )} + 2 \cos{\left (x \right )}$$

In [10]:
expr.diff(x)


Out[10]:
$$2 \sin{\left (x \right )} \cos{\left (x \right )} - 2 \sin{\left (x \right )}$$

In [11]:
expr.diff(x).diff(x)


Out[11]:
$$- 2 \sin^{2}{\left (x \right )} + 2 \cos^{2}{\left (x \right )} - 2 \cos{\left (x \right )}$$

And then can generate code


In [12]:
ccode(expr.diff(x).diff(x))


Out[12]:
'-2*pow(sin(x), 2) + 2*pow(cos(x), 2) - 2*cos(x)'

Combining reasoning and code generation gives us more efficient code


In [13]:
expr.diff(x).diff(x)


Out[13]:
$$- 2 \sin^{2}{\left (x \right )} + 2 \cos^{2}{\left (x \right )} - 2 \cos{\left (x \right )}$$

In [14]:
simplify(expr.diff(x).diff(x))


Out[14]:
$$- 2 \cos{\left (x \right )} + 2 \cos{\left (2 x \right )}$$

In [15]:
ccode(simplify(expr.diff(x).diff(x)))  # Faster code


Out[15]:
'-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.