sympy
Comprehensive guide for SymPy - Python library for symbolic mathematics. Use for symbolic expressions, calculus (derivatives, integrals, limits, series), equation solving (algebraic, differential, systems), linear algebra, simplification, matrix operations, special functions, code generation, and mathematical proofs. Essential for analytical mathematics and computer algebra.
What this skill does
# SymPy - Symbolic Mathematics
Python library for symbolic mathematics, providing computer algebra system (CAS) capabilities entirely in Python.
## When to Use
- Symbolic expressions and algebraic manipulation
- Calculus (derivatives, integrals, limits, series expansions)
- Solving equations (algebraic, transcendental, differential)
- Simplification and transformation of expressions
- Matrix operations and linear algebra (symbolic)
- Special mathematical functions
- Mathematical proofs and verification
- Code generation (C, Fortran, LaTeX)
- Physics calculations (mechanics, quantum mechanics)
- Number theory and discrete mathematics
- Logic and Boolean algebra
- Geometric algebra
## Reference Documentation
**Official docs**: https://docs.sympy.org/
**Search patterns**: `sympy.symbols`, `sympy.diff`, `sympy.integrate`, `sympy.solve`, `sympy.simplify`
## Core Principles
### Use SymPy For
| Task | Module | Example |
|------|--------|---------|
| Symbols | `symbols` | `x, y = symbols('x y')` |
| Derivatives | `diff` | `diff(x**2, x)` |
| Integrals | `integrate` | `integrate(x**2, x)` |
| Equation solving | `solve` | `solve(x**2 - 4, x)` |
| Simplification | `simplify` | `simplify(expr)` |
| Limits | `limit` | `limit(sin(x)/x, x, 0)` |
| Series expansion | `series` | `series(exp(x), x, 0, 5)` |
| Matrices | `Matrix` | `Matrix([[1, 2], [3, 4]])` |
### Do NOT Use For
- Numerical computing (use NumPy, SciPy)
- Fast numerical calculations (symbolic is slow)
- Machine learning (use PyTorch, TensorFlow)
- Statistical analysis (use SciPy, statsmodels)
- Large-scale numerical simulations (use NumPy, Numba)
## Quick Reference
### Installation
```bash
# pip
pip install sympy
# conda
conda install sympy
# With all optional dependencies
pip install sympy[all]
```
### Standard Imports
```python
# Core imports
import sympy as sp
from sympy import symbols, Symbol, Function
from sympy import diff, integrate, limit, series
# Common operations
from sympy import simplify, expand, factor, collect
from sympy import solve, solveset, dsolve
# Special functions
from sympy import sin, cos, exp, log, sqrt, Abs
from sympy import pi, E, I, oo # Constants
# Matrices
from sympy import Matrix, eye, zeros, ones
# Printing
from sympy import init_printing, pprint, latex
init_printing() # Pretty printing in notebook
```
### Basic Pattern - Symbolic Expression
```python
from sympy import symbols, simplify, expand
# Define symbols
x, y, z = symbols('x y z')
# Create expression
expr = (x + y)**2
# Expand
expanded = expand(expr)
print(f"Expanded: {expanded}") # x**2 + 2*x*y + y**2
# Factor back
from sympy import factor
factored = factor(expanded)
print(f"Factored: {factored}") # (x + y)**2
# Substitute values
result = expr.subs([(x, 2), (y, 3)])
print(f"Result: {result}") # 25
```
### Basic Pattern - Calculus
```python
from sympy import symbols, diff, integrate, limit
from sympy import sin, cos, exp
x = symbols('x')
# Derivative
f = x**3 + 2*x**2 - x + 1
df = diff(f, x)
print(f"f'(x) = {df}") # 3*x**2 + 4*x - 1
# Integral
integral = integrate(sin(x), x)
print(f"∫sin(x)dx = {integral}") # -cos(x)
# Definite integral
definite = integrate(x**2, (x, 0, 1))
print(f"∫₀¹ x²dx = {definite}") # 1/3
# Limit
lim = limit(sin(x)/x, x, 0)
print(f"lim(sin(x)/x) as x→0 = {lim}") # 1
```
## Critical Rules
### ✅ DO
- **Use symbols() for variables** - Define symbolic variables properly
- **Simplify expressions** - Use simplify() to clean up results
- **Use rational numbers** - Use Rational(1, 2) instead of 0.5
- **Check assumptions** - Set assumptions on symbols when needed
- **Use subs() for substitution** - Replace symbols with values
- **Pretty print results** - Use pprint() or init_printing()
- **Verify results numerically** - Convert to float for checking
- **Use appropriate functions** - Choose right solving function
- **Factor before solving** - Simplify equations first
- **Use lambdify for speed** - Convert to NumPy functions
### ❌ DON'T
- **Mix symbolic and numeric carelessly** - Be explicit with types
- **Use Python floats in symbolic** - Use Rational or Integer
- **Forget to define symbols** - Must declare before use
- **Ignore symbolic/numeric distinction** - Know when to use each
- **Use == for equation solving** - Use solve() or Eq()
- **Evaluate expensive operations blindly** - Some integrals are hard
- **Assume automatic simplification** - Often need explicit simplify()
- **Use symbolic for large numerical tasks** - Too slow
- **Forget assumptions** - Can affect results (positive, real, etc.)
- **Over-rely on solve()** - Use solveset() for better handling
## Anti-Patterns (NEVER)
```python
from sympy import symbols, solve, simplify, integrate, Rational
import sympy as sp
# ❌ BAD: Using float instead of Rational
x = symbols('x')
expr = x + 0.5 # Float!
# Result may not be exact
# ✅ GOOD: Use Rational for exact arithmetic
expr = x + Rational(1, 2)
# Exact representation
# ❌ BAD: Not defining symbols
result = y**2 + 2*y + 1 # NameError: y not defined
# ✅ GOOD: Define symbols first
y = symbols('y')
result = y**2 + 2*y + 1
# ❌ BAD: Using Python == for equations
solve(x**2 == 4) # Wrong! Returns boolean
# ✅ GOOD: Use solve() properly
solve(x**2 - 4, x) # Returns [-2, 2]
# Or use Eq()
from sympy import Eq
solve(Eq(x**2, 4), x)
# ❌ BAD: Not simplifying
expr = (x + 1)**2 - (x**2 + 2*x + 1)
print(expr) # Messy, not simplified to 0
# ✅ GOOD: Simplify
result = simplify(expr)
print(result) # 0
# ❌ BAD: Using symbolic for numerical loops
for i in range(1000000):
result = sp.sin(sp.pi * i / 180) # Very slow!
# ✅ GOOD: Lambdify for numerical work
import numpy as np
x = symbols('x')
f_sym = sp.sin(x)
f_num = sp.lambdify(x, f_sym, 'numpy')
results = f_num(np.linspace(0, np.pi, 1000000)) # Fast!
# ❌ BAD: Ignoring assumptions
x = symbols('x')
sqrt(x**2) # Returns sqrt(x**2), not x (could be negative)
# ✅ GOOD: Set assumptions
x = symbols('x', positive=True)
simplify(sqrt(x**2)) # Returns x
```
## Symbols and Expressions
### Creating Symbols
```python
from sympy import symbols, Symbol
# Single symbol
x = Symbol('x')
# Multiple symbols
x, y, z = symbols('x y z')
# With assumptions
x = symbols('x', real=True)
y = symbols('y', positive=True)
n = symbols('n', integer=True)
theta = symbols('theta', real=True)
# Complex symbols
z = symbols('z', complex=True)
# Functions
from sympy import Function
f = Function('f')
g = Function('g')
# Indexed symbols
from sympy import IndexedBase, Idx
A = IndexedBase('A')
i, j = symbols('i j', integer=True)
element = A[i, j]
print(f"Assumptions for x: {x.assumptions0}")
```
### Building Expressions
```python
from sympy import symbols, sin, cos, exp, log, sqrt
from sympy import pi, E, I, oo
x, y, z = symbols('x y z')
# Arithmetic
expr1 = x + 2*y - 3*z
expr2 = x**2 + y**2
expr3 = x*y / z
# Functions
expr4 = sin(x) + cos(y)
expr5 = exp(x**2)
expr6 = log(x + 1)
# Constants
expr7 = pi * x
expr8 = E**x
expr9 = I * x # Imaginary unit
# Complex expressions
expr10 = (x + y)**3 / (sqrt(x**2 + y**2))
expr11 = sin(x)**2 + cos(x)**2
# Accessing parts of expressions
print(f"Numerator: {expr3.as_numer_denom()[0]}")
print(f"Denominator: {expr3.as_numer_denom()[1]}")
# Expression info
print(f"Free symbols: {expr10.free_symbols}")
print(f"Is polynomial: {expr1.is_polynomial()}")
```
### Substitution
```python
from sympy import symbols, sin, cos, pi
x, y = symbols('x y')
# Basic substitution
expr = x**2 + 2*x + 1
result = expr.subs(x, 3)
print(f"Result: {result}") # 16
# Multiple substitutions
expr = x**2 + y**2
result = expr.subs([(x, 1), (y, 2)])
print(f"Result: {result}") # 5
# Substitute expression
expr = sin(x) + cos(x)
result = expr.subs(x, pi/4)
print(f"Result: {result}") # sqrt(2)
# Sequential substitution
expr = x + y
temp = expr.subs(x, y)
result = temp.subs(y, 1)
print(f"Result: {result}") # 2
# Substitute and simplify
from sympy import simplify
expr = sin(x)**2 + cos(x)**2
result = siRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.