SymPy - Symbolic Mathematics in Python

Comprehensive tutorial on SymPy, Python's powerful symbolic mathematics library for computer algebra systems and mathematical computations.


What is SymPy?

SymPy is a Python library for symbolic mathematics. Unlike numerical libraries like NumPy, SymPy manipulates mathematical expressions symbolically, allowing exact computation with variables, equations, and functions.

Unlike numerical libraries that work with floating-point numbers, SymPy maintains exact symbolic representations, making it ideal for algebraic manipulations, calculus, and analytical solutions.

Getting Started with SymPy

Installation and Import

pip install sympy
import sympy as sp
from sympy import symbols, Eq, solve, diff, integrate, simplify

Creating Symbolic Variables

# Create symbols
x, y, z = symbols('x y z')

# Create symbols with assumptions
a = symbols('a', real=True, positive=True)
n = symbols('n', integer=True, positive=True)

Basic Symbolic Operations

Symbolic Expressions

# Create expressions
expr = (x + y)**2
expanded = sp.expand(expr)  # x**2 + 2*x*y + y**2

# Substitution
result = expr.subs(x, 1)  # (1 + y)**2

# Evaluation
numeric_result = expr.subs([(x, 2), (y, 3)])  # 25

Algebraic Manipulation

# Simplification
expr = x**2 - 2*x + 1
simplified = sp.simplify(expr)  # (x - 1)**2

# Factorization
expr = x**2 - 1
factored = sp.factor(expr)  # (x - 1)*(x + 1)

# Expansion
expr = (x + 1)**3
expanded = sp.expand(expr)  # x**3 + 3*x**2 + 3*x + 1

Solving Equations

Algebraic Equations

# Linear equation: 2*x + 3 = 7
solution = sp.solve(Eq(2*x + 3, 7), x)  # [2]

# Quadratic equation
solutions = sp.solve(x**2 - 4, x)  # [-2, 2]

# System of equations
eq1 = Eq(2*x + y, 5)
eq2 = Eq(x - y, 1)
solutions = sp.solve([eq1, eq2], [x, y])  # {x: 2, y: 1}

Differential Equations

# Define derivatives
f = sp.Function('f')
eq = Eq(f(x).diff(x, 2) + 9*f(x), 0)

# Solve second-order ODE
solution = sp.dsolve(eq, f(x))  # C1*sin(3*x) + C2*cos(3*x)

Calculus Operations

Differentiation

# Basic derivatives
f = x**3 + 2*x**2 - x + 1
df_dx = sp.diff(f, x)  # 3*x**2 + 4*x - 1

# Partial derivatives
g = x**2*y + y**3
dg_dx = sp.diff(g, x)      # 2*x*y
dg_dy = sp.diff(g, y)      # x**2 + 3*y**2

# Higher-order derivatives
d2f_dx2 = sp.diff(f, x, 2)  # 6*x + 4

Integration

# Indefinite integrals
integral = sp.integrate(x**2, x)  # x**3/3

# Definite integrals
def_integral = sp.integrate(x**2, (x, 0, 1))  # 1/3

# Multiple integrals
double_integral = sp.integrate(x*y, (x, 0, 2), (y, x, 2))

Limits and Series

# Limits
limit = sp.limit((x**2 - 1)/(x - 1), x, 1)  # 2

# Taylor series expansion
series = sp.series(sp.sin(x), x, 0, 6)  # x - x**3/6 + O(x**5)

Advanced Features

Matrix Operations

# Create matrices
A = sp.Matrix([[1, 2], [3, 4]])
B = sp.Matrix([[5, 6], [7, 8]])

# Matrix operations
C = A + B        # Addition
D = A * B        # Matrix multiplication
E = A.T          # Transpose
F = A.inv()      # Inverse
det = A.det()    # Determinant

Linear Algebra

# Eigenvalues and eigenvectors
eigenvals = A.eigenvals()
eigenvects = A.eigenvects()

# Solve systems linearly
b = sp.Matrix([1, 2])
x = A.solve(b)  # Solve A*x = b

Plotting and Visualization

2D Plotting

# Import plotting module
from sympy.plotting import plot

# Plot functions
p1 = plot(x**2, (x, -5, 5))
p2 = plot(sp.sin(x), sp.cos(x), (x, 0, 2*sp.pi))

3D Plotting

from sympy.plotting import plot3d

# 3D surface plots
plot3d(x**2 + y**2, (x, -1, 1), (y, -1, 1))

Applications in Science and Engineering

Physics

# Classical mechanics
from sympy.physics import mechanics
from sympy.physics.mechanics import dynamicsymbols

# Define generalized coordinates
q1, q2 = dynamicsymbols('q1 q2')
# Kinetic and potential energy calculations

Electrical Engineering

# Circuit analysis
from sympy.physics.control import *

# Transfer functions, Laplace transforms
s = symbols('s')
G = 1/(s**2 + 2*s + 1)  # Second-order system

Mathematics Education

# Generate practice problems
equations = sp.randprime(10, 100)**x - 1
solutions = sp.solve(equations, x)

Integration with Other Libraries

NumPy Integration

# Convert between symbolic and numerical
import numpy as np

# Symbolic to numerical function
f_symbolic = sp.sin(x)
f_numerical = sp.lambdify(x, f_symbolic, 'numpy')

# Evaluate numerically
x_vals = np.linspace(0, 2*np.pi, 100)
y_vals = f_numerical(x_vals)

Matplotlib Visualization

import matplotlib.pyplot as plt

# Create symbolic function
f = sp.exp(-x**2) * sp.sin(3*x)

# Convert to numerical function
f_num = sp.lambdify(x, f, 'numpy')

# Plot
x_vals = np.linspace(-2, 2, 1000)
plt.plot(x_vals, f_num(x_vals))
plt.show()

Performance Considerations

Numerical vs Symbolic Computation

Memory Usage

# Complex expressions can be memory-intensive
expr = sp.expand((1 + x)**100)  # Creates 101 terms
len(str(expr))  # Very long expression

Best Practices

Code Organization

# Use descriptive variable names
kinetic_energy = (1/2) * mass * velocity**2
potential_energy = mass * gravity * height

# Group related expressions
equations = [Eq(force, mass * acceleration),
             Eq(acceleration, (force_friction + force_applied) / mass)]

Error Handling

try:
    solution = sp.solve(quadratic, x)
    # Process solution
except:
    print("Equation could not be solved symbolically")
    # Fallback to numerical methods

SymPy represents one of the most powerful computer algebra systems available in Python. Its ability to handle symbolic mathematics makes it invaluable for analytical work in mathematics, physics, engineering, and many other scientific fields.

This comprehensive guide covers the essential features of SymPy. For more advanced topics, explore the official documentation and community resources.

Updated: January 15, 2025
Author: Danial Pahlavan
Category: Python Libraries