1. 基本操作
1.1 导入库
from sympy import *
1.2 符号变量定义
x, y, z = symbols("x y z")
1.3 替换变量
expr = cos(x) + 1
expr.subs(x,y) # p.subs(old, new)
# 输出:cos(y) + 1
expr.subs(x,0)
# 输出:2
expr.subs(x,x**y)
# 输出:cos(x**y) + 1
expr = sin(2*x) + cos(2*x)
expand_trig(expr)
# 输出:2*sin(x)*cos(x) + 2*cos(x)**2 - 1
expr.subs(sin(2*x), 2*sin(x)*cos(x))
# 输出:2*sin(x)*cos(x) + cos(2*x)
若一次替换多个变量:
expr = x**3 + 4*x*y - z
expr.subs([(x, 2), (y, 4), (z, 0)])
# 输出:40
1.4 字符串转符号表达式
str_expr = "x**2 + 3*x - 1/2"
expr = sympify(str_expr)
print(expr)
# 输出: x**2 + 3*x - 1/2
str_expr = "x**2 + 3*x - 0.5"
expr = sympify(str_expr)
print(expr)
# 输出: x**2 + 3*x - 0.5
注意:不要跟化简函数
simplify
搞混了!!!
1.5 将符号表达式计算结果转化为浮点数
expr = sqrt(8)
# 输出:2*sqrt(2)
expr.evalf()
# 输出:2.82842712474619
expr.evalf(4)
# 输出:2.828
expr = cos(2*x)
expr.evalf(subs={x: 2.4})
0.0874989834394464
# 有时计算结果会出现输入误差,如果想解决此问题,可按如下方式解决
one = cos(1)**2 + sin(1)**2
(one - 1).evalf()
# 输出:-0.e-124
(one - 1).evalf(chop=True)
# 输出:0