SymPy:符号运算库介绍 (1)

2019-05-06  本文已影响0人  autumn1919

1.1 欧拉恒等式

e^{i\pi}+1=0

In [1]: from sympy import * #导入sympy 库
In [2]: E**(I*pi)+1
Out[2]: 0

1.2 expand():展开表达式

从熟知的公式入手:
e^{ix}=cosx+isinx
应用sympy库的expand函数将e^{ix}展开:

In [4]: x=Symbol("x",real=true)  #定义x为实数
In [5]: expand(exp(I*x),complex=true)  #complex 设置表达式有实数与虚数部分
Out[5]: I*sin(x) + cos(x)

1.3 series():泰勒展开

e^{ix}进行泰勒展开:

In [6]: tmp=series(exp(I*x),x,0,10)
In [7]: tmp
Out[7]: 1 + I*x - x**2/2 - I*x**3/6 + x**4/24 + I*x**5/120 - x**6/720 - I*x**7/5040 + x**8/40320 + I*x**9/362880 + O(x**10)

根据欧拉公式,虚数项之和应等于sin(x)的泰勒级数,而实数项之和应等于cos(x)的展开。

 # 获得e^(ix)的实部
In [8]: re(tmp) 
Out[8]: x**8/40320 - x**6/720 + x**4/24 - x**2/2 + re(O(x**10)) + 1
# 对 cos(x)进行展开
In [9]: series(cos(x),x,0,10)
Out[9]: 1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 + O(x**10)
# 获得e^(ix)的虚部
In [10]: im(tmp)
Out[10]: x**9/362880 - x**7/5040 + x**5/120 - x**3/6 + x + im(O(x**10))
#对 sin(x)进行展开
In [11]: series(sin(x),x,0,10)
Out[11]: x - x**3/6 + x**5/120 - x**7/5040 + x**9/362880 + O(x**10)

1.4 integrate:积分的运算

\int xsin(x) d x=-xcos(x)+sin(x)

#计算不定积分
In [12]: integrate(x*sin(x),x)
Out[12]: -x*cos(x) + sin(x)

\int_0^{2\pi}xsin(x) d x =-2\pi

#计算定积分
In [13]: integrate(x*sin(x),(x,0,2*pi))
Out[13]: -2*pi

1.5 表达式操作

In [14]: simplify((x+2)**2-(x+1)**2)
Out[14]: 2*x + 3
In [15]: radsimp(1/(sqrt(5)+2*sqrt(2)))
Out[15]: (-sqrt(5) + 2*sqrt(2))/3
In [3]: x,y=symbols("x,y")
In [4]: radsimp(1/(y*sqrt(x)+x*sqrt(y)))
Out[4]: (-sqrt(x)*y + x*sqrt(y))/(x*y*(x - y))
In [5]: cancel((x**2-1)/(1+x))
Out[5]: x - 1
In [7]: s=symbols("s")
In [8]: trans_fun=1/(s**3+s**2+s+1)
In [9]: apart(trans_fun)
Out[9]: -(s - 1)/(2*(s**2 + 1)) + 1/(2*(s + 1))
上一篇 下一篇

猜你喜欢

热点阅读