sympy库的使用(六)解方程

一、方程式

SymPy中方程式不是用“=”表示相等,而是使用Eq

from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)

Eq(x, y)

还可以这样表达

solveset(Eq(x**2, 1), x)

solveset(Eq(x**2 - 1, 0), x)

#这里默认等于0
solveset(x**2 - 1, x)

二、求解方程

求解方程是要函数是solveset,使用语法是solveset(equation, variable=None, domain=S.Complexes),分别是等式(默认等于0,),变量,定义域。

请注意,函数solve也可以用于求解方程式,solve(equations, variables)

solveset(x**2 - x, x)

solveset(x - x, x, domain=S.Reals)

solveset(sin(x) - 1, x, domain=S.Reals)

 如果是无解,返回空,如果找不到解,返回表达式

solveset(exp(x), x)     # No solution exists

solveset(cos(x) - x, x)  # Not able to find solution

三、求线性方程组

求解线性方程组linsolve

方程列表形式:

linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))

 矩阵形式:

只写前面的系数

linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))

 A * x = b形式

M = Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))
system = A, b = M[:, :-1], M[:, -1]
system
linsolve(system, x, y, z)

四、求非线性方程组

非线性方程组就是自变量和因变量不是线性关系

求解非线性方程组 的函数是nonlinsolve

1.当存在实解时

这个例子我不明白是什么意思,为什么这个解时这个??

a, b, c, d = symbols('a, b, c, d', real=True)
nonlinsolve([a**2 + a, a - b], [a, b])
nonlinsolve([x*y - 1, x - 2], x, y)

 现在解读一下上面2个例子

第一个:a**2+a = 0,a-b=0,a**2+a=0推出a=0或者a=-1,将2个解代入a-b=0,即可得到b=0或者b=-1

第二个:x*y-1=0,x-2=0,前面等式推出y=1/x,后面等式推出x=2,就得到结果了

 

2.当存在复数解时

都看不懂这个复数,直接跳过,复数使用的也不多

nonlinsolve([x**2 + 1, y**2 + 1], [x, y])

 

3.存在真实和复数解时,实部虚部

from sympy import sqrt
system = [x**2 - 2*y**2 -2, x*y - 2]
vars = [x, y]
nonlinsolve(system, vars)

4.具有无数个解

下面这个例子,第一个表达式x*y=0,推出x=0,y任意数或者y=0,x任意数,第二个表达式x*y-x=0 可以简化x*(y-1)=0推出x=0,y任意数或者y=1,x任意数,综合一起可得,x=0,y任意数

nonlinsolve([x*y, x*y - x], [x, y])

5.注意点

(1)解的顺序与给定符号的顺序相对应,也就是说解和对应变量对应

(2)如果nonlinsolve返回的是数值,热不是表达式,如果返回的是表达式,可以使用solve

(3)nonlinsolve尚不能解三角函数的方程组,但是solve可以(但不能给出所有的解,因为三角函数的解实在是太多了,无限循环的)

solve([sin(x + y), cos(x - y)], [x, y])

 solveset会得到多个解,roots会得到第一个跟是什么,第二个跟是什么,跟和第几以字典形式

五、解微分方程

定义一个未知方程的微分

f, g = symbols('f g', cls=Function)
f(x).diff(x)

 表示微分方程 f′′(x)2f(x)+f(x)=sin(x)因此我们将使用

diffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))
diffeq

 解微分方程

dsolve(diffeq, f(x))

 解未知表达式的微分方程

dsolve(f(x).diff(x)*(1 - sin(f(x))) - 1, f(x))

原文地址:https://www.cnblogs.com/cgmcoding/p/14680457.html