About

This notebook was created to follow the sympy code generation tutorial at this link


In [6]:
from sympy import *
init_printing()

In [7]:
pi.evalf(10)


Out[7]:
$$\pi$$

In [32]:
alpha, beta, gamma, x, y = symbols('alpha beta gamma x y')
alpha, beta


Out[32]:
$$\left ( \alpha, \quad \beta\right )$$

In [14]:
f= Function('f')

In [31]:
diff(sin(x+1)*cos(y), x, y)


Out[31]:
$$- \sin{\left (y \right )} \cos{\left (x + 1 \right )}$$

In [28]:
test = diff(f(x)+1,x)
test


Out[28]:
$$\frac{d}{d x} f{\left (x \right )}$$

In [46]:
Md = Function('M_d')(x)
Md


Out[46]:
$$\operatorname{M_{d}}{\left (x \right )}$$

In [42]:
q1, q2, q3 = symbols('q_1 q_2 q_3')
q = Matrix([q1, q2, q3])
q


Out[42]:
$$\left[\begin{matrix}q_{1}\\q_{2}\\q_{3}\end{matrix}\right]$$

In [71]:
acol = Matrix([q1**2+sin(q2), exp(q3), q2-q1])
J = acol.jacobian(q)
J


Out[71]:
$$\left[\begin{matrix}2 q_{1} & \cos{\left (q_{2} \right )} & 0\\0 & 0 & e^{q_{3}}\\-1 & 1 & 0\end{matrix}\right]$$

In [52]:
n, m = symbols('n m', integer=True)
M = MatrixSymbol('M', n, m)
b = MatrixSymbol('b', m, 1)
M*b


Out[52]:
$$M b$$

In [69]:
(M*b).T


Out[69]:
$$b^T M^T$$

In [ ]:
(M*b).T

In [57]:
Transpose(M*b).doit()


Out[57]:
$$b^T M^T$$

In [60]:
A = IndexedBase('A')
i = Idx('i')
A[2], A[i]


Out[60]:
$$\left ( A_{2}, \quad A_{i}\right )$$

Code printing


In [62]:
x = symbols('x')
expr = abs(sin(x**2))
expr


Out[62]:
$$\left|{\sin{\left (x^{2} \right )}}\right|$$

In [74]:
ccode(expr)


Out[74]:
'fabs(sin(pow(x, 2)))'

In [73]:
tanh(x).rewrite(exp)


Out[73]:
$$\frac{e^{x} - e^{- x}}{e^{x} + e^{- x}}$$

make python functions from expressions the easy way


In [ ]: