MCP HubMCP Hub
스킬 목록으로 돌아가기

sympy

K-Dense-AI
업데이트됨 Today
26,534
2,743
26,534
GitHub에서 보기
메타general

정보

이 Claude 스킬은 Python에서 대수학, 미적분학, 방정식 풀이, 기호 선형대수를 위한 정확한 기호 수학 연산을 가능하게 합니다. 수치적 근사치가 아닌 정밀한 기호 조작이 필요할 때 이상적이며, lambdify를 통한 코드 생성과 LaTeX 출력 기능을 포함합니다. NumPy/SciPy의 부동소수점 근사치가 수학적 작업에 부족할 때 이 스킬을 사용하세요.

빠른 설치

Claude Code

추천
기본
npx skills add K-Dense-AI/claude-scientific-skills -a claude-code
플러그인 명령대체
/plugin add https://github.com/K-Dense-AI/claude-scientific-skills
Git 클론대체
git clone https://github.com/K-Dense-AI/claude-scientific-skills.git ~/.claude/skills/sympy

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

SymPy - Symbolic Mathematics in Python

Overview

SymPy is a Python library for symbolic mathematics that enables exact computation using mathematical symbols rather than numerical approximations. This skill provides comprehensive guidance for performing symbolic algebra, calculus, linear algebra, equation solving, physics calculations, and code generation using SymPy.

Installation

Tested against SymPy 1.14.0 (stable; April 2025). Requires Python 3.9+.

# Install SymPy using uv
uv pip install "sympy>=1.14"

# Optional: for lambdify and plotting examples
uv pip install numpy scipy matplotlib

Check your version:

import sympy
print(sympy.__version__)

When to Use This Skill

Use this skill when:

  • Solving equations symbolically (algebraic, differential, systems of equations)
  • Performing calculus operations (derivatives, integrals, limits, series)
  • Manipulating and simplifying algebraic expressions
  • Working with matrices and linear algebra symbolically
  • Doing physics calculations (mechanics, quantum mechanics, vector analysis)
  • Number theory computations (primes, factorization, modular arithmetic)
  • Geometric calculations (2D/3D geometry, analytic geometry)
  • Converting mathematical expressions to executable code (Python, C, Fortran)
  • Generating LaTeX or other formatted mathematical output
  • Needing exact mathematical results (e.g., sqrt(2) not 1.414...)

Core Capabilities

1. Symbolic Computation Basics

Creating symbols and expressions:

from sympy import symbols, Symbol
x, y, z = symbols('x y z')
expr = x**2 + 2*x + 1

# With assumptions
x = symbols('x', real=True, positive=True)
n = symbols('n', integer=True)

Simplification and manipulation:

from sympy import simplify, expand, factor, cancel
simplify(sin(x)**2 + cos(x)**2)  # Returns 1
expand((x + 1)**3)  # x**3 + 3*x**2 + 3*x + 1
factor(x**2 - 1)    # (x - 1)*(x + 1)

For detailed basics: See references/core-capabilities.md

2. Calculus

Derivatives:

from sympy import diff
diff(x**2, x)        # 2*x
diff(x**4, x, 3)     # 24*x (third derivative)
diff(x**2*y**3, x, y)  # 6*x*y**2 (partial derivatives)

Integrals:

from sympy import integrate, oo
integrate(x**2, x)              # x**3/3 (indefinite)
integrate(x**2, (x, 0, 1))      # 1/3 (definite)
integrate(exp(-x), (x, 0, oo))  # 1 (improper)

Limits and Series:

from sympy import limit, series
limit(sin(x)/x, x, 0)  # 1
series(exp(x), x, 0, 6)  # 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)

For detailed calculus operations: See references/core-capabilities.md

3. Equation Solving

Algebraic equations:

from sympy import solveset, solve, Eq
solveset(x**2 - 4, x)  # {-2, 2}
solve(Eq(x**2, 4), x)  # [-2, 2]

Systems of equations:

from sympy import linsolve, nonlinsolve
linsolve([x + y - 2, x - y], x, y)  # {(1, 1)} (linear)
nonlinsolve([x**2 + y - 2, x + y**2 - 3], x, y)  # (nonlinear)

Differential equations:

from sympy import Function, dsolve, Derivative
f = symbols('f', cls=Function)
dsolve(Derivative(f(x), x) - f(x), f(x))  # Eq(f(x), C1*exp(x))

For detailed solving methods: See references/core-capabilities.md

4. Matrices and Linear Algebra

Matrix creation and operations:

from sympy import Matrix, eye, zeros
M = Matrix([[1, 2], [3, 4]])
M_inv = M**-1  # Inverse
M.det()        # Determinant
M.T            # Transpose

Eigenvalues and eigenvectors:

eigenvals = M.eigenvals()  # {eigenvalue: multiplicity}
eigenvects = M.eigenvects()  # [(eigenval, mult, [eigenvectors])]
P, D = M.diagonalize()  # M = P*D*P^-1

Solving linear systems:

A = Matrix([[1, 2], [3, 4]])
b = Matrix([5, 6])
x = A.solve(b)  # Solve Ax = b

For comprehensive linear algebra: See references/matrices-linear-algebra.md

5. Physics and Mechanics

Classical mechanics:

from sympy.physics.mechanics import dynamicsymbols, LagrangesMethod
from sympy import symbols

# Define system
q = dynamicsymbols('q')
m, g, l = symbols('m g l')

# Lagrangian (T - V)
L = m*(l*q.diff())**2/2 - m*g*l*(1 - cos(q))

# Apply Lagrange's method
LM = LagrangesMethod(L, [q])

Vector analysis:

from sympy.physics.vector import ReferenceFrame, dot, cross
N = ReferenceFrame('N')
v1 = 3*N.x + 4*N.y
v2 = 1*N.x + 2*N.z
dot(v1, v2)  # Dot product
cross(v1, v2)  # Cross product

Quantum mechanics:

from sympy.physics.quantum import Ket, Bra, Operator, Commutator
A, B = Operator('A'), Operator('B')
psi = Ket('psi')
comm = Commutator(A, B).doit()

For detailed physics capabilities: See references/physics-mechanics.md

6. Advanced Mathematics

The skill includes comprehensive support for:

  • Geometry: 2D/3D analytic geometry, points, lines, circles, polygons, transformations
  • Number Theory: Primes, factorization, GCD/LCM, modular arithmetic, Diophantine equations
  • Combinatorics: Permutations, combinations, partitions, group theory
  • Logic and Sets: Boolean logic, set theory, finite and infinite sets
  • Statistics: Probability distributions, random variables, expectation, variance
  • Special Functions: Gamma, Bessel, orthogonal polynomials, hypergeometric functions
  • Polynomials: Polynomial algebra, roots, factorization, Groebner bases

For detailed advanced topics: See references/advanced-topics.md

7. Code Generation and Output

Convert to executable functions:

from sympy import lambdify
import numpy as np

expr = x**2 + 2*x + 1
f = lambdify(x, expr, 'numpy')  # Create NumPy function
x_vals = np.linspace(0, 10, 100)
y_vals = f(x_vals)  # Fast numerical evaluation

Generate C/Fortran code:

from sympy.utilities.codegen import codegen
[(c_name, c_code), (h_name, h_header)] = codegen(
    ('my_func', expr), 'C'
)

LaTeX output:

from sympy import latex
latex_str = latex(expr)  # Convert to LaTeX for documents

For comprehensive code generation: See references/code-generation-printing.md

Working with SymPy: Best Practices

1. Always Define Symbols First

from sympy import symbols
x, y, z = symbols('x y z')
# Now x, y, z can be used in expressions

2. Use Assumptions for Better Simplification

x = symbols('x', positive=True, real=True)
sqrt(x**2)  # Returns x (not Abs(x)) due to positive assumption

Common assumptions: real, positive, negative, integer, rational, complex, even, odd

3. Use Exact Arithmetic

from sympy import Rational, S
# Correct (exact):
expr = Rational(1, 2) * x
expr = S(1)/2 * x

# Incorrect (floating-point):
expr = 0.5 * x  # Creates approximate value

4. Numerical Evaluation When Needed

from sympy import pi, sqrt
result = sqrt(8) + pi
result.evalf()    # 5.96371554103586
result.evalf(50)  # 50 digits of precision

5. Convert to NumPy for Performance

# Slow for many evaluations:
for x_val in range(1000):
    result = expr.subs(x, x_val).evalf()

# Fast:
f = lambdify(x, expr, 'numpy')
results = f(np.arange(1000))

6. Use Appropriate Solvers

  • solveset: Algebraic equations (primary)
  • linsolve: Linear systems
  • nonlinsolve: Nonlinear systems
  • dsolve: Differential equations
  • solve: General purpose (legacy, but flexible)

Reference Files Structure

This skill uses modular reference files for different capabilities:

  1. core-capabilities.md: Symbols, algebra, calculus, simplification, equation solving

    • Load when: Basic symbolic computation, calculus, or solving equations
  2. matrices-linear-algebra.md: Matrix operations, eigenvalues, linear systems

    • Load when: Working with matrices or linear algebra problems
  3. physics-mechanics.md: Classical mechanics, quantum mechanics, vectors, units

    • Load when: Physics calculations or mechanics problems
  4. advanced-topics.md: Geometry, number theory, combinatorics, logic, statistics

    • Load when: Advanced mathematical topics beyond basic algebra and calculus
  5. code-generation-printing.md: Lambdify, codegen, LaTeX output, printing

    • Load when: Converting expressions to code or generating formatted output

Common Use Case Patterns

Pattern 1: Solve and Verify

from sympy import symbols, solve, simplify
x = symbols('x')

# Solve equation
equation = x**2 - 5*x + 6
solutions = solve(equation, x)  # [2, 3]

# Verify solutions
for sol in solutions:
    result = simplify(equation.subs(x, sol))
    assert result == 0

Pattern 2: Symbolic to Numeric Pipeline

# 1. Define symbolic problem
x, y = symbols('x y')
expr = sin(x) + cos(y)

# 2. Manipulate symbolically
simplified = simplify(expr)
derivative = diff(simplified, x)

# 3. Convert to numerical function
f = lambdify((x, y), derivative, 'numpy')

# 4. Evaluate numerically
results = f(x_data, y_data)

Pattern 3: Document Mathematical Results

# Compute result symbolically
integral_expr = Integral(x**2, (x, 0, 1))
result = integral_expr.doit()

# Generate documentation
print(f"LaTeX: {latex(integral_expr)} = {latex(result)}")
print(f"Pretty: {pretty(integral_expr)} = {pretty(result)}")
print(f"Numerical: {result.evalf()}")

Integration with Scientific Workflows

With NumPy

import numpy as np
from sympy import symbols, lambdify

x = symbols('x')
expr = x**2 + 2*x + 1

f = lambdify(x, expr, 'numpy')
x_array = np.linspace(-5, 5, 100)
y_array = f(x_array)

With Matplotlib

import matplotlib.pyplot as plt
import numpy as np
from sympy import symbols, lambdify, sin

x = symbols('x')
expr = sin(x) / x

f = lambdify(x, expr, 'numpy')
x_vals = np.linspace(-10, 10, 1000)
y_vals = f(x_vals)

plt.plot(x_vals, y_vals)
plt.show()

With SciPy

from scipy.optimize import fsolve
from sympy import symbols, lambdify

# Define equation symbolically
x = symbols('x')
equation = x**3 - 2*x - 5

# Convert to numerical function
f = lambdify(x, equation, 'numpy')

# Solve numerically with initial guess
solution = fsolve(f, 2)

Quick Reference: Most Common Functions

# Symbols
from sympy import symbols, Symbol
x, y = symbols('x y')

# Basic operations
from sympy import simplify, expand, factor, collect, cancel
from sympy import sqrt, exp, log, sin, cos, tan, pi, E, I, oo

# Calculus
from sympy import diff, integrate, limit, series, Derivative, Integral

# Solving
from sympy import solve, solveset, linsolve, nonlinsolve, dsolve

# Matrices
from sympy import Matrix, eye, zeros, ones, diag

# Logic and sets
from sympy import And, Or, Not, Implies, FiniteSet, Interval, Union

# Output
from sympy import latex, pprint, lambdify, init_printing

# Utilities
from sympy import evalf, N, nsimplify

Getting Started Examples

Example 1: Solve Quadratic Equation

from sympy import symbols, solve, sqrt
x = symbols('x')
solution = solve(x**2 - 5*x + 6, x)
# [2, 3]

Example 2: Calculate Derivative

from sympy import symbols, diff, sin
x = symbols('x')
f = sin(x**2)
df_dx = diff(f, x)
# 2*x*cos(x**2)

Example 3: Evaluate Integral

from sympy import symbols, integrate, exp
x = symbols('x')
integral = integrate(x * exp(-x**2), (x, 0, oo))
# 1/2

Example 4: Matrix Eigenvalues

from sympy import Matrix
M = Matrix([[1, 2], [2, 1]])
eigenvals = M.eigenvals()
# {3: 1, -1: 1}

Example 5: Generate Python Function

from sympy import symbols, lambdify
import numpy as np
x = symbols('x')
expr = x**2 + 2*x + 1
f = lambdify(x, expr, 'numpy')
f(np.array([1, 2, 3]))
# array([ 4,  9, 16])

Troubleshooting Common Issues

  1. "NameError: name 'x' is not defined"

    • Solution: Always define symbols using symbols() before use
  2. Unexpected numerical results

    • Issue: Using floating-point numbers like 0.5 instead of Rational(1, 2)
    • Solution: Use Rational() or S() for exact arithmetic
  3. Slow performance in loops

    • Issue: Using subs() and evalf() repeatedly
    • Solution: Use lambdify() to create a fast numerical function
  4. "Can't solve this equation"

    • Try different solvers: solve, solveset, nsolve (numerical)
    • Check if the equation is solvable algebraically
    • Use numerical methods if no closed-form solution exists
  5. Simplification not working as expected

    • Try different simplification functions: simplify, factor, expand, trigsimp
    • Add assumptions to symbols (e.g., positive=True)
    • Use simplify(expr, force=True) for aggressive simplification

Additional Resources

GitHub 저장소

K-Dense-AI/claude-scientific-skills
경로: skills/sympy
0
agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skills

연관 스킬

content-collections

메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기

polymarket

메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기

creating-opencode-plugins

메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기

sglang

메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기