sympy

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SymPy - Symbolic Mathematics in Python

SymPy - 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.
SymPy是一个用于符号数学的Python库,它支持使用数学符号进行精确计算,而非数值近似。本Skill提供了使用SymPy进行符号代数、微积分、线性代数、方程求解、物理计算以及代码生成的全面指南。

When to Use This Skill

何时使用该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...
    )
在以下场景中使用该Skill:
  • 符号化求解方程(代数方程、微分方程、方程组)
  • 执行微积分运算(求导、积分、极限、级数展开)
  • 操作和简化代数表达式
  • 符号化处理矩阵与线性代数相关任务
  • 进行物理计算(力学、量子力学、向量分析)
  • 数论计算(质数、因式分解、模运算)
  • 几何计算(2D/3D几何、解析几何)
  • 将数学表达式转换为可执行代码(Python、C、Fortran)
  • 生成LaTeX或其他格式的数学输出
  • 需要精确的数学结果(例如,返回
    sqrt(2)
    而非
    1.414...

Core Capabilities

核心功能

1. Symbolic Computation Basics

1. 符号计算基础

Creating symbols and expressions:
python
from sympy import symbols, Symbol
x, y, z = symbols('x y z')
expr = x**2 + 2*x + 1
创建符号与表达式:
python
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:**
```python
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
x = symbols('x', real=True, positive=True) n = symbols('n', integer=True)

**化简与操作:**
```python
from sympy import simplify, expand, factor, cancel
simplify(sin(x)**2 + cos(x)**2)  # 返回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. Calculus

2. 微积分

Derivatives:
python
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:
python
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:
python
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
求导:
python
from sympy import diff
diff(x**2, x)        # 2*x
diff(x**4, x, 3)     # 24*x(三阶导数)
diff(x**2*y**3, x, y)  # 6*x*y**2(偏导数)
积分:
python
from sympy import integrate, oo
integrate(x**2, x)              # x**3/3(不定积分)
integrate(x**2, (x, 0, 1))      # 1/3(定积分)
integrate(exp(-x), (x, 0, oo))  # 1(反常积分)
极限与级数:
python
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. Equation Solving

3. 方程求解

Algebraic equations:
python
from sympy import solveset, solve, Eq
solveset(x**2 - 4, x)  # {-2, 2}
solve(Eq(x**2, 4), x)  # [-2, 2]
Systems of equations:
python
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:
python
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
代数方程:
python
from sympy import solveset, solve, Eq
solveset(x**2 - 4, x)  # {-2, 2}
solve(Eq(x**2, 4), x)  # [-2, 2]
方程组:
python
from sympy import linsolve, nonlinsolve
linsolve([x + y - 2, x - y], x, y)  # {(1, 1)}(线性方程组)
nonlinsolve([x**2 + y - 2, x + y**2 - 3], x, y)  # (非线性方程组)
微分方程:
python
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. Matrices and Linear Algebra

4. 矩阵与线性代数

Matrix creation and operations:
python
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:
python
eigenvals = M.eigenvals()  # {eigenvalue: multiplicity}
eigenvects = M.eigenvects()  # [(eigenval, mult, [eigenvectors])]
P, D = M.diagonalize()  # M = P*D*P^-1
Solving linear systems:
python
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
矩阵创建与运算:
python
from sympy import Matrix, eye, zeros
M = Matrix([[1, 2], [3, 4]])
M_inv = M**-1  # 逆矩阵
M.det()        # 行列式
M.T            # 转置
特征值与特征向量:
python
eigenvals = M.eigenvals()  # {特征值: 重数}
eigenvects = M.eigenvects()  # [(特征值, 重数, [特征向量])]
P, D = M.diagonalize()  # M = P*D*P^-1
线性方程组求解:
python
A = Matrix([[1, 2], [3, 4]])
b = Matrix([5, 6])
x = A.solve(b)  # 求解Ax = b
线性代数全面指南: 参见
references/matrices-linear-algebra.md

5. Physics and Mechanics

5. 物理与力学

Classical mechanics:
python
from sympy.physics.mechanics import dynamicsymbols, LagrangesMethod
from sympy import symbols
经典力学:
python
from sympy.physics.mechanics import dynamicsymbols, LagrangesMethod
from sympy import symbols

Define system

定义系统

q = dynamicsymbols('q') m, g, l = symbols('m g l')
q = dynamicsymbols('q') m, g, l = symbols('m g l')

Lagrangian (T - V)

拉格朗日量(T - V)

L = m*(lq.diff())**2/2 - mgl(1 - cos(q))
L = m*(lq.diff())**2/2 - mgl(1 - cos(q))

Apply Lagrange's method

应用拉格朗日方法

LM = LagrangesMethod(L, [q])

**Vector analysis:**
```python
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:
python
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
LM = LagrangesMethod(L, [q])

**向量分析:**
```python
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)  # 点积
cross(v1, v2)  # 叉积
量子力学:
python
from sympy.physics.quantum import Ket, Bra, Commutator
psi = Ket('psi')
A = Operator('A')
comm = Commutator(A, B).doit()
物理功能详情: 参见
references/physics-mechanics.md

6. Advanced Mathematics

6. 高等数学

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
本Skill全面支持以下高等数学领域:
  • 几何: 2D/3D解析几何、点、线、圆、多边形、变换
  • 数论: 质数、因式分解、最大公约数/最小公倍数、模运算、丢番图方程
  • 组合数学: 排列、组合、分拆、群论
  • 逻辑与集合: 布尔逻辑、集合论、有限集与无限集
  • 统计学: 概率分布、随机变量、期望、方差
  • 特殊函数: Gamma函数、贝塞尔函数、正交多项式、超几何函数
  • 多项式: 多项式代数、根、因式分解、Groebner基
高等数学详情: 参见
references/advanced-topics.md

7. Code Generation and Output

7. 代码生成与输出

Convert to executable functions:
python
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:
python
from sympy.utilities.codegen import codegen
[(c_name, c_code), (h_name, h_header)] = codegen(
    ('my_func', expr), 'C'
)
LaTeX output:
python
from sympy import latex
latex_str = latex(expr)  # Convert to LaTeX for documents
For comprehensive code generation: See
references/code-generation-printing.md
转换为可执行函数:
python
from sympy import lambdify
import numpy as np

expr = x**2 + 2*x + 1
f = lambdify(x, expr, 'numpy')  # 创建NumPy函数
x_vals = np.linspace(0, 10, 100)
y_vals = f(x_vals)  # 快速数值计算
生成C/Fortran代码:
python
from sympy.utilities.codegen import codegen
[(c_name, c_code), (h_name, h_header)] = codegen(
    ('my_func', expr), 'C'
)
LaTeX输出:
python
from sympy import latex
latex_str = latex(expr)  # 转换为LaTeX格式用于文档
代码生成全面指南: 参见
references/code-generation-printing.md

Working with SymPy: Best Practices

使用SymPy的最佳实践

1. Always Define Symbols First

1. 始终先定义符号

python
from sympy import symbols
x, y, z = symbols('x y z')
python
from sympy import symbols
x, y, z = symbols('x y z')

Now x, y, z can be used in expressions

现在可以在表达式中使用x、y、z

undefined
undefined

2. Use Assumptions for Better Simplification

2. 使用假设条件以优化化简效果

python
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
python
x = symbols('x', positive=True, real=True)
sqrt(x**2)  # 由于设置了正数假设,返回x(而非Abs(x))
常见假设条件:
real
positive
negative
integer
rational
complex
even
odd

3. Use Exact Arithmetic

3. 使用精确算术

python
from sympy import Rational, S
python
from sympy import Rational, S

Correct (exact):

正确(精确):

expr = Rational(1, 2) * x expr = S(1)/2 * x
expr = Rational(1, 2) * x expr = S(1)/2 * x

Incorrect (floating-point):

错误(浮点数近似):

expr = 0.5 * x # Creates approximate value
undefined
expr = 0.5 * x # 生成近似值
undefined

4. Numerical Evaluation When Needed

4. 必要时进行数值计算

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

5. Convert to NumPy for Performance

5. 转换为NumPy以提升性能

python
undefined
python
undefined

Slow for many evaluations:

多次计算时速度较慢:

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

Fast:

快速计算:

f = lambdify(x, expr, 'numpy') results = f(np.arange(1000))
undefined
f = lambdify(x, expr, 'numpy') results = f(np.arange(1000))
undefined

6. Use Appropriate Solvers

6. 使用合适的求解器

  • solveset
    : Algebraic equations (primary)
  • linsolve
    : Linear systems
  • nonlinsolve
    : Nonlinear systems
  • dsolve
    : Differential equations
  • solve
    : General purpose (legacy, but flexible)
  • solveset
    :代数方程(首选)
  • linsolve
    :线性方程组
  • nonlinsolve
    :非线性方程组
  • dsolve
    :微分方程
  • solve
    :通用求解器(旧版,但灵活性高)

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
本Skill采用模块化参考文件来分类不同功能:
  1. core-capabilities.md
    :符号、代数、微积分、化简、方程求解
    • 加载场景:基础符号计算、微积分或方程求解任务
  2. matrices-linear-algebra.md
    :矩阵运算、特征值、线性方程组
    • 加载场景:处理矩阵或线性代数问题
  3. physics-mechanics.md
    :经典力学、量子力学、向量、单位
    • 加载场景:物理计算或力学问题
  4. advanced-topics.md
    :几何、数论、组合数学、逻辑、统计学
    • 加载场景:基础代数与微积分之外的高等数学主题
  5. code-generation-printing.md
    :Lambdify、代码生成、LaTeX输出、打印
    • 加载场景:将表达式转换为代码或生成格式化输出

Common Use Case Patterns

常见用例模式

Pattern 1: Solve and Verify

模式1:求解与验证

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

Solve equation

解方程

equation = x**2 - 5*x + 6 solutions = solve(equation, x) # [2, 3]
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
undefined
for sol in solutions: result = simplify(equation.subs(x, sol)) assert result == 0
undefined

Pattern 2: Symbolic to Numeric Pipeline

模式2:符号到数值的工作流

python
undefined
python
undefined

1. Define symbolic problem

1. 定义符号化问题

x, y = symbols('x y') expr = sin(x) + cos(y)
x, y = symbols('x y') expr = sin(x) + cos(y)

2. Manipulate symbolically

2. 符号化操作

simplified = simplify(expr) derivative = diff(simplified, x)
simplified = simplify(expr) derivative = diff(simplified, x)

3. Convert to numerical function

3. 转换为数值函数

f = lambdify((x, y), derivative, 'numpy')
f = lambdify((x, y), derivative, 'numpy')

4. Evaluate numerically

4. 数值计算

results = f(x_data, y_data)
undefined
results = f(x_data, y_data)
undefined

Pattern 3: Document Mathematical Results

模式3:记录数学结果

python
undefined
python
undefined

Compute result symbolically

符号化计算结果

integral_expr = Integral(x**2, (x, 0, 1)) result = integral_expr.doit()
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()}")
undefined
print(f"LaTeX: {latex(integral_expr)} = {latex(result)}") print(f"美化输出: {pretty(integral_expr)} = {pretty(result)}") print(f"数值结果: {result.evalf()}")
undefined

Integration with Scientific Workflows

与科学工作流的集成

With NumPy

与NumPy集成

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

与Matplotlib集成

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

与SciPy集成

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

Define equation symbolically

符号化定义方程

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

Convert to numerical function

转换为数值函数

f = lambdify(x, equation, 'numpy')
f = lambdify(x, equation, 'numpy')

Solve numerically with initial guess

给定初始猜测值进行数值求解

solution = fsolve(f, 2)
undefined
solution = fsolve(f, 2)
undefined

Quick Reference: Most Common Functions

快速参考:最常用函数

python
undefined
python
undefined

Symbols

符号

from sympy import symbols, Symbol x, y = symbols('x y')
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
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
from sympy import diff, integrate, limit, series, Derivative, Integral

Solving

求解

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

Matrices

矩阵

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

Logic and sets

逻辑与集合

from sympy import And, Or, Not, Implies, FiniteSet, Interval, Union
from sympy import And, Or, Not, Implies, FiniteSet, Interval, Union

Output

输出

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

Utilities

工具函数

from sympy import evalf, N, nsimplify
undefined
from sympy import evalf, N, nsimplify
undefined

Getting Started Examples

快速入门示例

Example 1: Solve Quadratic Equation

示例1:求解二次方程

python
from sympy import symbols, solve, sqrt
x = symbols('x')
solution = solve(x**2 - 5*x + 6, x)
python
from sympy import symbols, solve, sqrt
x = symbols('x')
solution = solve(x**2 - 5*x + 6, x)

[2, 3]

[2, 3]

undefined
undefined

Example 2: Calculate Derivative

示例2:计算导数

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

2xcos(x**2)

2xcos(x**2)

undefined
undefined

Example 3: Evaluate Integral

示例3:计算积分

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

1/2

1/2

undefined
undefined

Example 4: Matrix Eigenvalues

示例4:矩阵特征值

python
from sympy import Matrix
M = Matrix([[1, 2], [2, 1]])
eigenvals = M.eigenvals()
python
from sympy import Matrix
M = Matrix([[1, 2], [2, 1]])
eigenvals = M.eigenvals()

{3: 1, -1: 1}

{3: 1, -1: 1}

undefined
undefined

Example 5: Generate Python Function

示例5:生成Python函数

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

array([ 4, 9, 16])

undefined
undefined

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
  1. "NameError: name 'x' is not defined"
    • 解决方案:使用
      symbols()
      函数先定义符号,再使用它们
  2. 数值结果不符合预期
    • 问题:使用了
      0.5
      这类浮点数而非
      Rational(1, 2)
    • 解决方案:使用
      Rational()
      S()
      进行精确算术运算
  3. 循环中计算速度缓慢
    • 问题:反复使用
      subs()
      evalf()
    • 解决方案:使用
      lambdify()
      创建快速数值函数
  4. "Can't solve this equation"
    • 尝试不同的求解器:
      solve
      solveset
      nsolve
      (数值求解)
    • 检查方程是否存在代数解
    • 若不存在闭式解,可使用数值方法
  5. 化简结果不符合预期
    • 尝试不同的化简函数:
      simplify
      factor
      expand
      trigsimp
    • 为符号添加假设条件(例如
      positive=True
    • 使用
      symplify(expr, force=True)
      强制进行深度化简

Additional Resources

额外资源