SymPy Symbolic Mathematics & Computer Algebra

Module 5 • Session 37 • Allocation: 1 Contact Hr

sympy symbols calculus algebra lambdify

SymPy is a full-featured Computer Algebra System (CAS) written entirely in Python. Unlike numerical libraries like NumPy or SciPy, SymPy retains analytical exactness by treating variables as mathematical symbols rather than floating-point numbers.

1. Defining Symbolic Variables and Basic Expressions

Before creating algebraic expressions, you must explicitly declare symbols using symbols() or Symbol().

import sympy as sp # Declare symbolic variables x, y, z = sp.symbols('x y z') # Form algebraic expression expr = x**2 + 2*x*y + y**2 print("Symbolic Expression:", expr) print("Evaluated with x=2, y=3:", expr.subs({x: 2, y: 3}))
Key Difference: In plain Python, x = 2 assigns an integer. In SymPy, x = sp.symbols('x') creates a symbolic object that represents the mathematical variable $x$.

2. Algebraic Simplification and Expansion

SymPy provides powerful algorithms to simplify complex expressions, factor polynomials, and expand algebraic terms.

Function Description Example Use Case
sp.expand() Expands polynomial product terms sp.expand((x + y)**3)
sp.factor() Factors expressions into irreducible terms sp.factor(x**2 - y**2)
sp.simplify() Applies heuristic mathematical simplifications sp.simplify(sp.sin(x)**2 + sp.cos(x)**2)
sp.trigsimp() Simplifies trigonometric identities specifically sp.trigsimp(sp.sin(x)/sp.cos(x))
import sympy as sp x, y = sp.symbols('x y') # Algebraic Expansion poly = (x + 2)*(x - 5) expanded = sp.expand(poly) print("Expanded Poly:", expanded) # x**2 - 3*x - 10 # Trigonometric Simplification trig_expr = sp.sin(x)**2 + sp.cos(x)**2 simplified = sp.simplify(trig_expr) print("Simplified Trig:", simplified) # 1

3. Solving Algebraic & System of Equations

The sp.solve() function finds exact algebraic roots for single equations or systems of linear/non-linear equations.

Example 1: Solving a Quadratic Equation

Solve $ax^2 + bx + c = 0$ symbolically for $x$:

import sympy as sp x, a, b, c = sp.symbols('x a b c') # Set equation equal to zero: a*x**2 + b*x + c = 0 roots = sp.solve(a*x**2 + b*x + c, x) print("Root 1:", roots[0]) print("Root 2:", roots[1])

Example 2: Solving Simultaneous Linear Equations

Solve the system: $2x + y = 5$ and $x - 3y = -8$

import sympy as sp x, y = sp.symbols('x y') eq1 = sp.Eq(2*x + y, 5) eq2 = sp.Eq(x - 3*y, -8) solution = sp.solve((eq1, eq2), (x, y)) print("System Solution:", solution) # {x: 1, y: 3}

4. Symbolic Calculus: Derivatives, Integrals & Limits

SymPy performs analytical calculus, allowing exact symbolic differentiation, integration, limit calculations, and Taylor series expansion.

import sympy as sp x = sp.symbols('x') f = sp.sin(x) * sp.exp(x) # Symbolic Derivative (d/dx) diff_f = sp.diff(f, x) print("Derivative:", diff_f) # exp(x)*sin(x) + exp(x)*cos(x) # Indefinite Integration indef_int = sp.integrate(sp.cos(x), x) print("Indefinite Integral:", indef_int) # sin(x) # Definite Integration (from x=0 to x=pi/2) def_int = sp.integrate(sp.sin(x), (x, 0, sp.pi/2)) print("Definite Integral Value:", def_int) # 1 # Symbolic Limit as x -> 0 lim_val = sp.limit(sp.sin(x)/x, x, 0) print("Limit (sin(x)/x as x->0):", lim_val) # 1

5. Bridging SymPy and NumPy: lambdify()

When you need fast numerical evaluations over large arrays after symbolic manipulation, use sp.lambdify() to convert SymPy analytical expressions directly into high-speed NumPy vectorized functions.

import sympy as sp import numpy as np x = sp.symbols('x') symbolic_expr = sp.sin(x) + x**2 # Convert to NumPy-compatible function func_numpy = sp.lambdify(x, symbolic_expr, 'numpy') # Numerical evaluation across a NumPy array x_vals = np.linspace(0, 10, 5) y_vals = func_numpy(x_vals) print("NumPy Array Input:", x_vals) print("Evaluated Output:", y_vals)
Performance Tip: Symbolic evaluation via expr.subs() is slow for large datasets. Always use sp.lambdify() when generating data points for numerical plotting or model execution.

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Algebraic Factorization

Declare symbols $x$ and $y$. Define the polynomial $x^3 - 3x^2y + 3xy^2 - y^3$ and factor it using sp.factor().

Challenge 2: Higher-Order Derivative

Define $f(x) = x^5 - 4x^3 + 2x$. Compute its 3rd order derivative $\frac{d^3f}{dx^3}$ using sp.diff(f, x, 3).

Challenge 3: System Solver

Solve the non-linear system $x^2 + y^2 = 25$ and $y - x = 1$ for $(x, y)$ using sp.solve().

⚡ Interactive Sandbox (SymPy CAS Engine)
Console Output:
Click "Run Code" above to execute SymPy algebraic computations...

📝 Knowledge Check Quiz

1. What is the main purpose of SymPy compared to NumPy?
2. Which function converts a SymPy symbolic expression into a fast NumPy-compatible numerical function?
3. How do you construct an equation $2x + 1 = 5$ explicitly in SymPy?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)