SymPy
是一个用于符号数学计算的 Python 库,它提供了一个强大的工具集,用于符号数学、代数、微积分、离散数学和量子物理等领域。SymPy 的核心功能包括符号表达式的创建和操作、符号微分、积分、方程求解、矩阵运算以及数论等。
安装
pip install sympy
使用
「基本代数运算」
from sympy import symbols, expand
# 定义符号
x, y, z = symbols('x y z')
# 定义表达式并展开
expr = (x + y + z)**2
expanded_expr = expand(expr)
print("Expanded Expression:", expanded_expr)
「求解代数方程」
from sympy import symbols, solve
# 定义符号
x = symbols('x')
# 定义方程
equation = x**2 - 4
# 求解方程
solutions = solve(equation, x)
print("Solutions of the equation:", solutions)
「求导和积分」
from sympy import symbols, diff, integrate
# 定义符号
x = symbols('x')
# 定义函数
f = x**3
# 求导
f_prime = diff(f, x)
# 积分
f_integral = integrate(f, x)
print("Derivative of f:", f_prime)
print("Integral of f:", f_integral)
「矩阵运算」
from sympy import symbols, Matrix, Eq, solve
# 定义符号
x = symbols('x')
# 创建矩阵
A = Matrix([[1, 2], [3, 4]])
B = Matrix([x, 1])
# 解线性方程组 Ax = B
solutions_matrix = solve(Eq(A, B), x)
print("Solutions of the linear system:", solutions_matrix)
「极限计算」
from sympy import symbols, limit
# 定义符号
x = symbols('x')
# 定义函数
f = 1/x
# 计算极限
limit_value = limit(f, x, 0, '+')
print("Limit of f as x approaches 0 from the positive side:", limit_value)
「级数展开」
from sympy import symbols, series
# 定义符号
x = symbols('x')
# 定义函数
f = 1/(1 - x)
# 级数展开
series_expansion = series(f, x, n=10)
print("Series expansion of f:", series_expansion)
「微分方程求解」
from sympy import symbols, Function, diff, Eq, solve
# 定义符号
x = symbols('x')
f = Function('f')(x)
# 定义微分方程
diff_eq = Eq(diff(f, x), x**2)
# 求解微分方程
solutions_diff_eq = solve(diff_eq, f)
print("Solutions of the differential equation:", solutions_diff_eq)
「符号积分变换」
from sympy import symbols, fourier_transform, laplace_transform
# 定义符号
x, w = symbols('x w')
# 定义函数
f = x**2
# 傅里叶变换
fourier_transformed = fourier_transform(f, x, w)
# 拉普拉斯变换
laplace_transformed = laplace_transform(f, x, s)
print("Fourier Transform:", fourier_transformed)
print("Laplace Transform:", laplace_transformed)
「使用特殊函数」
from sympy import symbols, sin, cos, exp, pi
# 定义符号
x = symbols('x')
# 定义函数
expr = sin(x) + cos(x) + exp(-x)
print("Expression with special functions:", expr)
「符号逻辑运算」
from sympy import symbols, Or, And, Not, simplify_logic
# 定义符号
x, y = symbols('x y')
# 定义逻辑表达式
expr1 = Or(x, y)
expr2 = And(x, Not(y))
# 简化逻辑表达式
simplified_expr = simplify_logic(expr1 & expr2)
print("Simplified logical expression:", simplified_expr)