python的符号运算主要依靠sympy
(symbol py)库
有两种方法:sp.symbols
或sp.var
import sympy as sp
x,y = sp.symbols('x,y') # 定义符号变量x,y
#--------------
sp.var('x1,x2',positive = True,integer = True) # 定义符号变量x1,x2,
x = sp.var('x:2') # 定义符号数组,用的多
import sympy as sp
f,g = sp.symbols('f,g',cls = sp.Function) # 定义符号函数f,g
t = sp.Function('t')
#-----------
sp.var('f,g',cls = sp.Function) # 定义符号函数f,g
使用
sp,solve(func,*symbols)
求解符号方程
例1:求符号方程 a x 2 + b x + c = 0 ax^2+bx+c=0 ax2+bx+c=0的解
import sympy as sp
a, b, c, x=sp.symbols('a,b,c,x')
x0=sp.solve(a*x**2+b*x+c, x)
print(x0)
结果:[(-b - sqrt(-4*a*c + b**2))/(2*a), (-b + sqrt(-4*a*c + b**2))/(2*a)]
例2:求方程组 { x 1 2 + x 2 2 = 1 x 1 = x 2 \left\{ \begin{matrix} x_1^2+x_2^2=1 \\ x_1=x_2 \end{matrix} \right. {x12+x22=1x1=x2的符号解
import sympy as sp
x = sp.var('x:2') #定义符号数组
s = sp.solve([x[0]**2+x[1]**2-1,x[0]-x[1]], x)
print(s)
结果:[(-sqrt(2)/2, -sqrt(2)/2), (sqrt(2)/2, sqrt(2)/2)]
$$
$$