[英]Euler's method for Python
我想近似 dy/dx = -x +1 的解,在 0 到 2 的區間上使用歐拉法。我正在使用這段代碼
def f(x):
return -x+1 # insert any function here
x0 = 1 # Initial slope #
dt = 0.1 # time step
T = 2 # ...from...to T
t = np.linspace(0, T, int(T/dt) + 1) # divide the interval from 0 to 2 by dt
x = np.zeros(len(t))
x[0] = x0 # value at 1 is the initial slope
for i in range(1, len(t)): # apply euler method
x[i] = x[i-1] + f(x[i-1])*dt
plt.figure() # plot the result
plt.plot(t,x,color='blue')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.show()
我可以使用此代碼在任何時間間隔內逼近任何 function 的解決方案嗎? 很難看出這是否真的有效,因為我不知道如何 plot 實際解決方案( -1/2x^2 + x )沿着近似值。
如果您始終為同一角色使用相同的變量名,這可能會有所幫助。 根據您的 output,解決方案是y(t)
。 因此,您的微分方程應該是dy(t)/dt = f(t,y(t))
。 這將給出斜率 function 及其精確解決方案的實現
def f(t,y): return 1-t
def exact_y(t,t0,y0): return y0+0.5*(1-t0)**2-0.5*(1-t)**2
然后將歐拉循環也作為單獨的 function 實現,盡可能保留問題的具體細節
def Eulerint(f,t0,y0,te,dt):
t = np.arange(t0,te+dt,dt)
y = np.zeros(len(t))
y[0] = y0
for i in range(1, len(t)): # apply euler method
y[i] = y[i-1] + f(t[i-1],y[i-1])*dt
return t,y
然后 plot 解決方案為
y0,T,dt = 1,2,0.1
t,y = Eulerint(f,0,y0,T,dt)
plt.plot(t,y,color='blue')
plt.plot(t,exact_y(t,0,y0),color='orange')
您可以使用 plot 實際解決方案:
def F(x):
return -0.5*x+x
# some code lines
plt.plot(t,x,color='blue')
plt.plot(t,F(t),color='orange')
但請注意,實際解決方案 (-1/2x+x = 1/2x) 與您的斜率f(x)不對應,並且會顯示不同的解決方案。
*實際解 (-1/2x+x = 1/2x) 的實際斜率 f(x)只是f(x)=1/2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.