jpskill.com
🛠️ 開発・MCP コミュニティ 🔴 エンジニア向け 👤 エンジニア・AI開発者

🛠️ Sympy

sympy

SymPyは、Pythonを使って数式を記号

⏱ ボイラープレート実装 半日 → 30分

📺 まず動画で見る(YouTube)

▶ 【衝撃】最強のAIエージェント「Claude Code」の最新機能・使い方・プログラミングをAIで効率化する超実践術を解説! ↗

※ jpskill.com 編集部が参考用に選んだ動画です。動画の内容と Skill の挙動は厳密には一致しないことがあります。

📜 元の英語説明(参考)

SymPy is a Python library for symbolic mathematics that enables exact computation using mathematical symbols rather than numerical approximations.

🇯🇵 日本人クリエイター向け解説

一言でいうと

SymPyは、Pythonを使って数式を記号

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o sympy.zip https://jpskill.com/download/3563.zip && unzip -o sympy.zip && rm sympy.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/3563.zip -OutFile "$d\sympy.zip"; Expand-Archive "$d\sympy.zip" -DestinationPath $d -Force; ri "$d\sympy.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して sympy.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → sympy フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-17
同梱ファイル
1

💬 こう話しかけるだけ — サンプルプロンプト

  • Sympy を使って、最小構成のサンプルコードを示して
  • Sympy の主な使い方と注意点を教えて
  • Sympy を既存プロジェクトに組み込む方法を教えて

これをClaude Code に貼るだけで、このSkillが自動発動します。

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

SymPy - Pythonでの数式処理

概要

SymPyは、数値近似ではなく数学記号を用いて厳密な計算を可能にする、数式処理のためのPythonライブラリです。このスキルは、SymPyを使用して記号代数、微積分、線形代数、方程式の解法、物理計算、およびコード生成を実行するための包括的なガイダンスを提供します。

このスキルを使用する場面

このスキルは、次のような場合に使用してください。

  • 方程式を記号的に解く場合(代数方程式、微分方程式、連立方程式)
  • 微積分演算を実行する場合(導関数、積分、極限、級数)
  • 代数式を操作および簡略化する場合
  • 行列と線形代数を記号的に扱う場合
  • 物理計算を行う場合(力学、量子力学、ベクトル解析)
  • 数論計算を行う場合(素数、因数分解、モジュラー演算)
  • 幾何学的計算を行う場合(2D/3D幾何学、解析幾何学)
  • 数式を実行可能なコードに変換する場合(Python、C、Fortran)
  • LaTeXまたはその他の形式の数式出力を生成する場合
  • 厳密な数学的結果が必要な場合(例:sqrt(2)ではなく1.414...

主要な機能

1. 記号計算の基本

記号と式の作成:

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)

簡略化と操作:

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)

詳細な基本については、 references/core-capabilities.md を参照してください。

2. 微積分

導関数:

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)

積分:

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)

極限と級数:

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)

詳細な微積分演算については、 references/core-capabilities.md を参照してください。

3. 方程式の解法

代数方程式:

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

連立方程式:

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)

微分方程式:

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))

詳細な解法については、 references/core-capabilities.md を参照してください。

4. 行列と線形代数

行列の作成と演算:

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

固有値と固有ベクトル:

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

線形システムの解法:

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

包括的な線形代数については、 references/matrices-linear-algebra.md を参照してください。

5. 物理学と力学

古典力学:

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])

ベクトル解析:

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

量子力学:

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

詳細な物理機能については、 references/physics-mechanics.md を参照してください。

6. 高度な数学

このスキルには、以下の包括的なサポートが含まれています。

  • 幾何学: 2D/3D解析幾何学、点、線、円、多角形、変換
  • 数論: 素数、因数分解、GCD/LCM、モジュラー演算、ディオファントス方程式
  • 組み合わせ論: 順列、組み合わせ、分割、群論
  • 論理と集合: ブール論理、集合論、有限集合と無限集合
  • 統計: 確率分布、確率変数、期待値、分散
  • 特殊関数: ガンマ関数、ベッセル関数、直交多項式、超幾何関数
  • 多項式: 多項式代数、根、因数分解、グレブナー基底

詳細な高度なトピックについては、 references/advanced-topics.md を参照してください。

7. コード生成と出力

実行可能な関数への変換:

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

C/Fortranコードの生成:

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

LaTeX出力:

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

包括的なコード生成については、 references/code-generation-printing.md を参照してください。

SymPyの操作:ベストプラクティス

1. 常に最初に記号を定義する

from sympy import symbols
x, y, z = symbols('x y z')
# Now x, y, z can be use
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

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.

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, Commutator
psi = Ket('psi')
A = Operator('A')
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

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.