P e x c e r a

Introduction to SymPy for Symbolic Math

NumPy works with numbers. SymPy works with symbols. Instead of approximating $\sqrt{2}$ as 1.41421..., SymPy keeps it as the exact expression $\sqrt{2}$. This allows you to derive formulas, simplify expressions, and solve equations exactly — without any floating-point error.


Symbols, Expressions, and Simplification

Everything starts with declaring symbolic variables using symbols(). From there, you build expressions as Python objects, and SymPy treats them algebraically.

Getting Started

<pre><code class="language-python">from sympy import symbols, sqrt, simplify, expand, factor x, y = symbols('x y') expr = (x + 1) ** 2 print(expand(expr)) # x**2 + 2*x + 1 print(factor(x**2 - 1)) # (x - 1)*(x + 1) # Exact arithmetic print(sqrt(8)) # 2*sqrt(2) (not 2.828...) </pre>

Symbolic Differentiation

SymPy can differentiate any expression exactly with diff(). This is how you verify your hand-derived gradients, derive backpropagation rules for custom activation functions, or quickly find critical points of a loss surface.

Differentiating Expressions

<pre><code class="language-python">from sympy import symbols, diff, exp, ln x = symbols('x') # Polynomial f = x**3 + 5*x**2 - 2 print(diff(f, x)) # 3*x**2 + 10*x # Sigmoid derivative sigmoid = 1 / (1 + exp(-x)) print(diff(sigmoid, x)) # exp(-x)/(1 + exp(-x))**2 # Which simplifies to sigmoid*(1 - sigmoid) # Second derivative print(diff(f, x, 2)) # 6*x + 10 </pre>

Solving Equations and Substitution

solve() finds the values of a variable where an expression equals zero. subs() replaces a symbol with a value, converting a symbolic expression into a number.

Solve and Substitute

<pre><code class="language-python">from sympy import symbols, solve, diff x = symbols('x') # Find critical points of f(x) = x^3 - 6x^2 + 9x f = x**3 - 6*x**2 + 9*x critical = solve(diff(f, x), x) print(critical) # [1, 3] # Evaluate the function at a critical point print(f.subs(x, 1)) # 4 print(f.subs(x, 3)) # 0 </pre>