求解方程

SymPy学习笔记(二)需要避免的坑中已经提到过,SymPy中表达相等应该用Eq()而不是===

用solveset(equation, x)可以求equation关于x的解集,如果等式右边是0,也可以不写成solveset(Eq(expr, 0), x),直接写成solveset(expr, x),例如:

1
2
3
4
>>> solveset(Eq(x**2, 1), x)
{-1, 1}
>>> solveset(x**2 - 1, x)
{-1, 1}

如果无解,将返回 \varnothing ,如果无法求解,会返回一个条件集合。

1
2
3
4
>>> solveset(exp(x), x)     # 无解

>>> solveset(cos(x) - x, x) # 无法求解
{x │ x ∊ ℂ ∧ (-x + cos(x) = 0)}

求解线性方程组

使用linsolve()

1
2
3
4
5
6
7
8
>>> linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z)) # 等式列表形式
{(-y - 1, y, 2)}
>>> linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z)) # 增广矩阵形式
{(-y - 1, y, 2)}
>>> M = Matrix(((1, 1, 1, 1), (1, 1, 2, 3))) # A*x = b 形式
system = A, b = M[:, :-1], M[:, -1]
linsolve(system, x, y, z)
{(-y - 1, y, 2)}

求解非线性方程组

使用nonlinsolve()

获得多项式的重根数

solveset()返回的都是不重复的根,要获得多项式的重根数,可以使用roots()

1
2
3
4
>>> solveset(x**3 - 6*x**2 + 9*x, x)
{0, 3}
>>> roots(x**3 - 6*x**2 + 9*x, x)
{0: 1, 3: 2}

求解微分方程

使用dsolve()

本文属于系列文章:SymPy学习笔记