簡體   English   中英

python代碼求解以下初值問題常微分方程在區間上使用歐拉法(o 10)

[英]python code to solve the following initial value problem ordinary differential equation using Euler method over the interval (o 10)

我有這個問題

編寫 python 代碼,使用歐拉法在區間 (o 10) 上以 10 個時間步長求解以下初值問題常微分方程。 A) y'= -y -y^2; y(0)=1 如果精確解是 y(t) = 1/(-1+2e^t) y(10) 處的絕對誤差是多少。 現在我已經寫了這段代碼

def pow_t(x,b):  
    t=1; 
    while (b):
        t*=x 
        b=b-1
    return t


def  absolute(): 
    y=[x for x in range(1,11)]
    
    h=0.0001 
    for i in range(1,10) :
       y[i]=y[i-1]+(h*(-1*y[i-1]-pow_t(y[i-1],2)))
       print("y",i,"=",y[i]) 
    
    exact = 0.0000227
    approx = y[9]
    absolute = exact - approx 
    print("abbsolute erroe = exact - approx ")
    print("abbsolute erroe = ",absolute)
   

print(absolute())

預期的 output 是這個

這是我得到的實際結果

我需要將 y 列表的第一個索引設置為 1,然后通過 for 循環填充列表的 rest,我該如何編碼?

如果您能在開始之前了解封閉式解決方案,這將很有幫助。

Equation: y' + y + y^2 = 0
Initial condition: y(0) = 1

這是一個伯努利方程。

封閉形式的解決方案是:

y(t) = e^C1 / (e^C1 - e^t)

應用初始條件求解常數 C1:

y(0) = e^C1 / (e^C1 - 1) = 1

你的初始條件不可能是正確的。 沒有滿足初始條件的常數。 請檢查並更正。

您的 output 基本上是正確的,但移動了 1 (例如,您的y10是預期的y9調用 y9 )並且未四舍五入到小數點后 4 位。

解決這些問題的一種方法是:

y = 1
t = 0
h = 0.0001
iterates = [1]

for i in range(10):
    print(f'y{i} = {y:.4f}')
    y = y+h*(-y-y**2)
    iterates.append(y)
    t += h
print(f'y10 = {y:.4f}')

請注意,此代碼僅使用標量變量y作為 Euler 方法中的變量(而不是數組中的條目。最終是一個口味問題,但這樣代碼看起來更干凈。

output 是:

y0 = 1.0000
y1 = 0.9998
y2 = 0.9996
y3 = 0.9994
y4 = 0.9992
y5 = 0.9990
y6 = 0.9988
y7 = 0.9986
y8 = 0.9984
y9 = 0.9982
y10 = 0.9980

與預期的 output 匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM