[英]solving differential equation with step function
我試圖解決這個微分方程作為我的任務的一部分。 我無法理解如何在代碼中輸入u的條件。 在下面顯示的代碼中,我隨意提供
u = 5.
2dx(t)dt=−x(t)+u(t)
5dy(t)dt=−y(t)+x(t)
u=2S(t−5)
x(0)=0
y(0)=0
where S(t−5) is a step function that changes from zero to one at t=5. When it is multiplied by two, it changes from zero to two at that same time, t=5
where S(t−5) is a step function that changes from zero to one at t=5. When it is multiplied by two, it changes from zero to two at that same time, t=5
。
def model(x,t,u):
dxdt = (-x+u)/2
return dxdt
def model2(y,x,t):
dydt = -(y+x)/5
return dydt
x0 = 0
y0 = 0
u = 5
t = np.linspace(0,40)
x = odeint(model,x0,t,args=(u,))
y = odeint(model2,y0,t,args=(u,))
plt.plot(t,x,'r-')
plt.plot(t,y,'b*')
plt.show()
我不太了解SciPy庫,但是對於文檔中的示例,我會嘗試這樣的事情:
def model(x, t, K, PT)
"""
The model consists of the state x in R^2, the time in R and the two
parameters K and PT regarding the input u as step function, where K
is the infimum of u and PT is the delay of the step.
"""
x1, x2 = x # Split the state into two variables
u = K if t>=PT else 0 # This is the system input
# Here comes the differential equation in vectorized form
dx = [(-x1 + u)/2,
(-x2 + x1)/5]
return dx
x0 = [0, 0]
K = 2
PT = 5
t = np.linspace(0,40)
x = odeint(model, x0, t, args=(K, PT))
plt.plot(t, x[:, 0], 'r-')
plt.plot(t, x[:, 1], 'b*')
plt.show()
這里有幾個問題,步進功能只是其中的一小部分。 您可以使用簡單的lambda
定義步進函數,然后只需從外部范圍捕獲它,甚至不將其傳遞給您的函數。 因為有時情況並非如此,我們將明確並通過它。 您的下一個問題是要集成的函數中的參數順序。 根據文檔 (y,t,...)。 即,首先是函數,然后是時間向量,然后是其他args
參數。 因此,對於第一部分,我們得到:
u = lambda t : 2 if t>5 else 0
def model(x,t,u):
dxdt = (-x+u(t))/2
return dxdt
x0 = 0
y0 = 0
t = np.linspace(0,40)
x = odeint(model,x0,t,args=(u,))
轉到下一部分,麻煩的是,你不能將x
作為arg提供給y,因為它是特定時間的x(t)
值的向量,因此y+x
在函數中沒有意義寫了。 如果傳遞x函數而不是x值,則可以從數學類中遵循直覺。 這樣做需要使用您感興趣的特定時間值插入x值(scipy可以處理,沒問題):
from scipy.interpolate import interp1d
xfunc = interp1d(t.flatten(),x.flatten(),fill_value="extrapolate")
#flatten cuz the shape is off , extrapolate because odeint will go out of bounds
def model2(y,t,x):
dydt = -(y+x(t))/5
return dydt
y = odeint(model2,y0,t,args=(xfunc,))
然后你得到:
@Sven的答案更像是scipy / numpy這樣的矢量編程。 但我希望我的回答能提供一條更清晰的路徑,從你已經知道的工作解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.