python - SymPy
pip install sympy
import sympy
# 虚数单位i
sympy.I # 𝑖
sympy.I ** 2 # -1
sympy.sqrt(-1) # 𝑖
# 自然对数的底e
sympy.E # e
sympy.log(sympy.E) # 1
# 无穷大
1/sympy.oo # 0
1+sympy.oo # oo
# 圆周率pi
sympy.pi # 𝜋
sympy.sin(sympy.pi/2) # 1
初等运算
# 求对数
sympy.log(sympy.E) # 1
sympy.log(100, 10) # 2
# 求平方根
sympy.sqrt(4) # 2
sympy.sqrt(-1) # 𝑖
# 求n次方根
sympy.root(8,3) # 2
# 求k次方
2**3 # 8
16**(1/2) # 4.0
# 求阶层
sympy.factorial(20) # 2432902008176640000
# 求三角函数
sympy.sin(sympy.pi) # 0
sympy.cos(sympy.pi) # -1
# 表达式与表达式求值
表达式与表达式求值
# 定义x为一个符号,表示为一个变量
x = sympy.Symbol('x')
f = 2*x + 1
# 使用evalf函数,传入变量x的值,对表达式进行求值
f.evalf(subs={x:4}) # 9.0
x, y = sympy.symbols('x y')
f = 2*x + y
f.evalf(subs={x:4,y:2}) # 10.0
f.evalf(subs={x:4}) # 𝑦+8.0
解方程
x = sympy.Symbol('x')
# 解方程 x - 2 = 0
sympy.solve(x - 2, x) # [2]
# 解方程 x^2 - 1 = 0
sympy.solve(x**2 - 1, x) # [-1, 1]
# 解方程 x^2 + 1 = 0
sympy.solve(x**2 + 1, x) # [-I, I]
f = x + 1
sympy.solve(f, x) # -1
# 解方程组
# x + y = 1
# x - y = 3
x, y = sympy.symbols('x y')
f1 = x + y - 1
f2 = x - y - 3
sympy.solve([f1, f2], [x, y]) # {x: 2, y: -1}
计算求和式
\(\displaystyle\sum_{n=1}^{100}2n\)
n = sympy.Symbol('n')
sympy.summation(2 * n, (n, 1, 100)) # 10100
求和式的方程
\(\displaystyle\sum_{i=1}^{5}x+10x=15\)
x = sympy.Symbol('x')
i = sympy.Symbol('i',integer = True)
f = sympy.summation(x,(i,1,5)) + 10 * x - 15
sympy.solve(f,x) # [1]
求极限
\(\displaystyle\lim_{x\rightarrow0}\frac{x}{sinx}=1\)
x = sympy.Symbol('x')
f = sympy.sin(x) / x
sympy.limit(f, x, 0) # 1
\(\displaystyle\lim_{x\rightarrow0}(1+x)^{\frac{1}{x}}=e\)
x = sympy.Symbol('x')
f = (1+x)**(1/x)
sympy.limit(f, x, 0) # e
\(\displaystyle\lim_{x\rightarrow+\infty}(1+{\frac{1}{x}})^{x}=e\)
x = sympy.Symbol('x')
f = (1+1/x)**x
sympy.limit(f, x, sympy.oo) # e
求导
x = sympy.Symbol('x')
f = x ** 2 + 2 * x + 1
sympy.diff(f,x) # 2𝑥+2
x = sympy.Symbol('x')
f = sympy.sin(x)
sympy.diff(f,x) # cos(𝑥)
x, y = sympy.symbols('x y')
f = x**2 + 2*x + y**3
sympy.diff(f,x) # 2𝑥+2
sympy.diff(f,y) # 3𝑦^2
定积分
\(\int_{0}^{1}{2x}dx\)
x = sympy.Symbol('x')
f = 2 * x
sympy.integrate(f,(x,0,1)) # 1
\(\int_{0}^{3}{\int_{0}^{x}{2x}dx}dx\)
x = sympy.Symbol('x')
f = 2 * x
g = sympy.integrate(f,(x,0,x)) # x^2
sympy.integrate(g,(x,0,3)) # 9
不定积分
\(\int(e^{x}+2x)dx\)
x = sympy.Symbol('x')
f = sympy.E**x + 2*x
sympy.integrate(f,x) # x^2 + e^2