SymPy
是一个用来处理数学符号的 Python 库,一个计算机代数系统(Computer Algebra System, CAS)。
两个在线版本的 SymPy:
声明符号变量
from sympy import Symbol, symbols
x, y = symbols('x, y')
n = Symbol('n')
因为 x, y
这类的符号很常用,所以 SymPy 将所有拉丁及希腊字符定义成了 Symbol
,而不需要再像上面那样去手工定义:
from sympy.abc import x, y
# 查看都有些定义好的符号
help(sympy.abc)
级数
\[e^x = \sum_{n=0}^{\infty}{\frac{x^n}{n!}}\]from sympy.abc import x, n
from sympy import Sum, factorial, oo
Sum(x**n/factorial(n), (n, 0, oo)).doit()
exp(x)
级数展开
\[e^x = 1 + x + \frac{x^2}{2} + \frac{x^3}{6} + \frac{x^4}{24} + \frac{x^5}{120} + o(x^6)\]from sympy import series, exp
## 在x=0处对函数e^x进行5阶展开
series(exp(x), x=x, x0=0, n=5)
1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)
表达式展开
\[(x + y)^2 = x^2 + 2xy + y^2\]from sympy.abc import x, y
from sympy import expand
expand((x+y)**2)
x**2 + 2*x*y + y**2
表达式化简
\[\sin^2 x + \cos^2 x = 1\]from sympy.abc import x
from sympy import simplify
from sympy import sin, cos
simplify(sin(x)**2 + cos(x)**2)
1
求极限
\[\lim_{x \rightarrow \infty} (1 + \frac{1}{x})^x = e\]from sympy.abc import x
from sympy import limit, oo
f = lambda x: (1 + 1/x)**x
limit(f(x), x, oo)
E
求微分
\[\sin^\prime x = \cos x\]from sympy.abc import x
from sympy import diff, sin
diff(sin(x), x)
cos(x)
求积分
不定积分
\[\int \ln x\,\mathrm{d}x = x\ln x - x + C\]from sympy.abc import x
from sympy import integrate, log
integrate(log(x), x)
x*log(x) - x
定积分
\[\int^\frac{\pi}{2}_0 \sin x\,\mathrm{d}x = 1\]from sympy.abc import x
from sympy import integrate, pi
integrate(sin(x), (x, 0, pi/2))
1
多项式因式分解
\[x^2 + 2x - 3 = (x - 1)(x + 3)\]from sympy.abc import x
from sympy import factor
f = x**2 + 2*x - 3
factor(f)
(x - 1)*(x + 3)
方程求解
\[x^4 - 1\]from sympy.abc import x
from sympy import solve
f = x**4 - 1
solve(f)
[-1, 1, -I, I]
线性代数 - Matrix
\[\begin{bmatrix} x & 1 \\ 1 & y \end{bmatrix}\]from sympy.abc import x, y
from sympy import Matrix
A = Matrix([[x, 1], [1, y]])
Matrix([
[x, 1],
[1, y]])