[英]Python scientific: interrupt differential equation solving with a condition
我目前正在使用odeint在python下解決一個微分方程系統,以模擬一個場中的帶電粒子(源於此包 ):
time = np.linspace(0, 5, 1000)
def sm(x, t):
return np.array([x[1], eta*Ez0(x[0])])
traj = odeint(sm,[0,1.], time)
它工作正常,但我想在x [0] <0時立即停止計算。目前,我只是阻止系統的發展:
def sm1(x, t):
if x[0] < 0:
return np.array([0, 0])
else:
return np.array([x[1], eta*Ez0(x[0])])
traj = odeint(sm1,[0,1.],time)
但我想有更好的解決方案。 我發現了這一點,但在我看來,它固定了步驟的數量,這是令人遺憾的。 任何建議表示贊賞。
如果編寫odeint函數的自定義擴展名,則可以使函數在完成時引發特定異常。 在Python中執行此操作可能會使其運行速度大大降低,但我認為您在C或Cython中編寫的內容相同。 請注意,我還沒有測試以下內容。
class ThatsEnoughOfThat(Exception):
pass
def custom_odeint(func, y0, t): # + whatever parameters you need
for timestep in t:
try:
# Do stuff. Call odeint/other scipy functions?
except ThatsEnoughOfThat:
break
return completedstuff
def sm2(x, t):
if x[0] < 0:
raise ThatsEnoughOfThat
return np.array([x[1], eta*Ez0(x[0])])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.