Communitygithub.com

sympy

파이썬에서 정확한 기호 수학이 필요할 때 사용합니다 — 대수학, 미적분학, 방정식 풀이, 기호 선형대수, lambdify/LaTeX을 통한 코드 생성. 부동소수점 근사로 충분한 경우 NumPy나 SciPy를 선호하세요.

sympy란 무엇인가요?

이 스킬은 Python용 기호 수학 라이브러리인 SymPy를 사용하여 정확한 수학 계산을 수행하는 방법을 안내합니다. SymPy는 수치 근사 대신 수학 기호를 사용한 정확한 계산을 가능하게 하여, 대수학, 미적분학, 방정식 풀이, 기호 선형대수, 물리학 계산, 코드 생성 등 다양한 작업에 활용할 수 있습니다. 이 스킬은 SymPy 1.14.0 버전을 기준으로 작성되었으며 Python 3.9+ 환경에서 사용 가능합니다. 주요 기능으로 기호 계산 기초, 미적분, 방정식 풀이 (solve, solveset, linsolve, dsolve 등), 행렬 및 선형대수, 물리 및 역학, 고급 수학, 코드 생성 및 출력의 7개 영역으로 구성되어 있으며, 각 영역에 대한 상세 참조 파일을 제공합니다. 특히 기호 표현식을 빠른 수치 함수로 변환하는 lambdify, LaTeX 출력, Matplotlib 및 SciPy와의 통합을 통해 과학 컴퓨팅 워크플로우에 쉽게 통합할 수 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/sympy

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

SymPy - Python에서의 기호 수학

개요

SymPy는 수치 근사 대신 수학 기호를 사용한 정확한 계산을 가능하게 하는 Python 기호 수학 라이브러리입니다. 이 스킬은 SymPy를 사용하여 기호 대수학, 미적분학, 선형대수학, 방정식 풀이, 물리학 계산 및 코드 생성을 수행하기 위한 포괄적인 지침을 제공합니다.

설치

SymPy 1.14.0 (안정 버전; 2025년 4월)에서 테스트되었습니다. Python 3.9+ 가 필요합니다.

# uv를 사용하여 SymPy 설치
uv pip install "sympy>=1.14"

# 선택 사항: lambdify 및 플롯 예제용
uv pip install numpy scipy matplotlib

버전 확인:

import sympy
print(sympy.__version__)

이 스킬을 사용해야 하는 경우

다음과 같은 경우에 이 스킬을 사용하세요:

  • 방정식을 기호적으로 풀 때 (대수, 미분, 연립방정식)
  • 미적분 연산을 수행할 때 (도함수, 적분, 극한, 급수)
  • 대수 표현식을 조작하고 단순화할 때
  • 행렬과 선형대수를 기호적으로 다룰 때
  • 물리학 계산을 할 때 (역학, 양자역학, 벡터 해석)
  • 정수론 계산을 할 때 (소수, 인수분해, 모듈러 연산)
  • 기하학 계산을 할 때 (2D/3D 기하학, 해석 기하학)
  • 수학 표현식을 실행 가능한 코드(Python, C, Fortran)로 변환할 때
  • LaTeX 또는 기타 형식화된 수학 출력을 생성할 때
  • 정확한 수학 결과가 필요할 때 (예: sqrt(2)가 1.414...가 아닌 경우)

핵심 기능

7가지 기능 영역은 references/core_capabilities.md에 문서화되어 있습니다:

  1. 기호 계산 기초 — 기호, 표현식, 단순화, 대입.
  2. 미적분학 — 미분, 적분, 극한, 급수.
  3. 방정식 풀이 — solve, solveset, 선형 및 비선형 연립방정식, 미분방정식.
  4. 행렬 및 선형대수학 — references/matrices-linear-algebra.md 참조.
  5. 물리학 및 역학 — references/physics-mechanics.md 참조.
  6. 고급 수학 — references/advanced-topics.md 참조.
  7. 코드 생성 및 출력 — references/code-generation-printing.md 참조.

처음 세 가지 영역에 대한 더 자세한 내용은 references/core-capabilities.md에 있습니다.

SymPy 작업 시 모범 사례

1. 항상 먼저 기호를 정의하세요

from sympy import symbols
x, y, z = symbols('x y z')
# 이제 x, y, z를 표현식에서 사용할 수 있습니다.

2. 더 나은 단순화를 위해 가정을 사용하세요

x = symbols('x', positive=True, real=True)
sqrt(x**2)  # x를 반환합니다 (양수 가정으로 인해 Abs(x)가 아님)

일반적인 가정: real, positive, negative, integer, rational, complex, even, odd

3. 정확한 연산을 사용하세요

from sympy import Rational, S
# 올바른 방법 (정확):
expr = Rational(1, 2) * x
expr = S(1)/2 * x

# 잘못된 방법 (부동소수점):
expr = 0.5 * x  # 근사값을 생성합니다.

4. 필요할 때 수치 평가를 사용하세요

from sympy import pi, sqrt
result = sqrt(8) + pi
result.evalf()    # 5.96371554103586
result.evalf(50)  # 50자리 정밀도

5. 성능 향상을 위해 NumPy로 변환하세요

# 여러 번 평가할 때 느림:
for x_val in range(1000):
    result = expr.subs(x, x_val).evalf()

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

6. 적절한 솔버를 사용하세요

  • solveset: 대수 방정식 (기본)
  • linsolve: 선형 연립방정식
  • nonlinsolve: 비선형 연립방정식
  • dsolve: 미분 방정식
  • solve: 일반 목적 (레거시이지만 유연함)

참조 파일 구조

이 스킬은 다양한 기능을 위해 모듈식 참조 파일을 사용합니다:

  1. core-capabilities.md: 기호, 대수, 미적분, 단순화, 방정식 풀이

    • 다음 경우에 로드: 기본 기호 계산, 미적분, 또는 방정식 풀이
  2. matrices-linear-algebra.md: 행렬 연산, 고유값, 선형 시스템

    • 다음 경우에 로드: 행렬 또는 선형대수 문제 작업 시
  3. physics-mechanics.md: 고전 역학, 양자 역학, 벡터, 단위

    • 다음 경우에 로드: 물리학 계산 또는 역학 문제 작업 시
  4. advanced-topics.md: 기하학, 정수론, 조합론, 논리, 통계

    • 다음 경우에 로드: 기본 대수 및 미적분을 넘어서는 고급 수학 주제 작업 시
  5. code-generation-printing.md: Lambdify, codegen, LaTeX 출력, 인쇄

    • 다음 경우에 로드: 표현식을 코드로 변환하거나 형식화된 출력 생성 시

일반적인 사용 사례 패턴

패턴 1: 풀고 검증하기

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

# 방정식 풀기
equation = x**2 - 5*x + 6
solutions = solve(equation, x)  # [2, 3]

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

패턴 2: 기호에서 수치로의 파이프라인

# 1. 기호 문제 정의
x, y = symbols('x y')
expr = sin(x) + cos(y)

# 2. 기호적으로 조작
simplified = simplify(expr)
derivative = diff(simplified, x)

# 3. 수치 함수로 변환
f = lambdify((x, y), derivative, 'numpy')

# 4. 수치적으로 평가
results = f(x_data, y_data)

패턴 3: 수학 결과 문서화

# 결과를 기호적으로 계산
integral_expr = Integral(x**2, (x, 0, 1))
result = integral_expr.doit()

# 문서 생성
print(f"LaTeX: {latex(integral_expr)} = {latex(result)}")
print(f"예쁘게: {pretty(integral_expr)} = {pretty(result)}")
print(f"수치: {result.evalf()}")

과학 워크플로우와의 통합

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)

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

SciPy와 함께

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

# 방정식을 기호적으로 정의
x = symbols('x')
equation = x**3 - 2*x - 5

# 수치 함수로 변환
f = lambdify(x, equation, 'numpy')

# 초기 추측값으로 수치적으로 풀기
solution = fsolve(f, 2)

빠른 참조: 가장 일반적인 함수

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

# 기본 연산
from sympy import simplify, expand, factor, collect, cancel
from sympy import sqrt, exp, log, sin, cos, tan, pi, E, I, oo

# 미적분
from sympy import diff, integrate, limit, series, Derivative, Integral

# 방정식 풀이
from sympy import solve, solveset, linsolve, nonlinsolve, dsolve

# 행렬
from sympy import Matrix, eye, zeros, ones, diag

# 논리 및 집합
from sympy import And, Or, Not, Implies, FiniteSet, Interval, Union

# 출력
from sympy import latex, pprint, lambdify, init_printing

# 유틸리티
from sympy import evalf, N, nsimplify

시작하기 예제

예제 1: 이차 방정식 풀기

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

예제 2: 도함수 계산

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

예제 3: 적분 평가

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

예제 4: 행렬 고유값

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

예제 5: Python 함수 생성

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

일반적인 문제 해결

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

    • 해결 방법: 사용 전에 항상 symbols()를 사용하여 기호를 정의하세요.
  2. 예상치 못한 수치 결과

    • 문제: Rational(1, 2) 대신 0.5와 같은 부동소수점 숫자를 사용한 경우
    • 해결 방법: 정확한 연산을 위해 Rational() 또는 S()를 사용하세요.
  3. 루프에서 성능 저하

    • 문제: subs()와 evalf()를 반복적으로 사용하는 경우
    • 해결 방법: lambdify()를 사용하여 빠른 수치 함수를 만드세요.
  4. "이 방정식을 풀 수 없습니다"

    • 다른 솔버 시도: solve, solveset, nsolve (수치)
    • 방정식이 대수적으로 풀 수 있는지 확인하세요.
    • 닫힌 형태의 해가 없으면 수치 방법을 사용하세요.
  5. 단순화가 예상대로 작동하지 않음

    • 다른 단순화 함수 시도: simplify, factor, expand, trigsimp
    • 기호에 가정을 추가하세요 (예: positive=True)
    • 적극적인 단순화를 위해 simplify(expr, force=True)를 사용하세요.

추가 자료

과학 에이전트 스킬 인용

이 스킬은 K-Dense의 Scientific Agent Skills의 일부입니다. 이것이 원고, 보고서, 프레젠테이션 또는 코드 릴리스에 실질적으로 기여한 경우, 참고 문헌 또는 소프트웨어 섹션에 논문을 추가하고 사용자에게 알리세요:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

항상 현재 버전을 인용하세요. DOI와 https://arxiv.org/abs/2609.00065는 최신 arXiv 버전으로 연결되므로 v1과 같은 버전 접미사를 추가하지 마세요. 네트워크에 접근 가능한 경우, 참조를 작성하기 전에 https://arxiv.org/abs/2609.00065 (또는 http://export.arxiv.org/api/query?id_list=2609.00065)를 가져와서 해당 레코드에서 저자 목록, 연도 및 버전을 가져오세요. 레코드에 저널 참조 또는 게시자 DOI가 있는 경우 대신 게시된 버전을 인용하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

관련 스킬