Python Sympy計算梯度、散度和旋度的例項
阿新 • • 發佈:2020-01-09
sympy有個vector 模組,裡面提供了求解標量場、向量場的梯度、散度、旋度等計算,官方參考連線:
http://docs.sympy.org/latest/modules/vector/index.html
sympy中計算梯度、散度和旋度主要有兩種方式:
一個是使用∇∇運算元,sympy提供了類Del(),該類的方法有:cross、dot和gradient,cross就是叉乘,計算旋度的,dot是點乘,用於計算散度,gradient自然就是計算梯度的。
另一種方法就是直接呼叫相關的API:curl、divergence和gradient,這些函式都在模組sympy.vector 下面。
使用sympy計算梯度、散度和旋度之前,首先要確定座標系,sympy.vector模組裡提供了構建座標系的類,常見的是笛卡爾座標系, CoordSys3D,根據下面的例子可以瞭解到相應應用。
(1)計算梯度
## 1 gradient C = CoordSys3D('C') delop = Del() # nabla運算元 # 標量場 f = x**2*y-xy f = C.x**2*C.y - C.x*C.y res = delop.gradient(f,doit=True) # 使用nabla運算元 # res = delop(f).doit() res = gradient(f) # 直接使用gradient print(res) # (2*C.x*C.y - C.y)*C.i + (C.x**2 - C.x)*C.j
(2)計算散度
## divergence C = CoordSys3D('C') delop = Del() # nabla運算元 # 向量場 f = x**2*y*i-xy*j f = C.x**2*C.y*C.i - C.x*C.y*C.j res = delop.dot(f,doit=True) # res = divergence(f) print(res) # 2*C.x*C.y - C.x,即2xy-x,向量場的散度是標量
(3)計算旋度
## curl C = CoordSys3D('C') delop = Del() # nabla運算元 # 向量場 f = x**2*y*i-xy*j f = C.x**2*C.y*C.i - C.x*C.y*C.j res = delop.cross(f,doit=True) # res = curl(f) print(res) # (-C.x**2 - C.y)*C.k,即(-x**2-y)*k,向量場的旋度是向量
以上這篇Python Sympy計算梯度、散度和旋度的例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。