#例題 5-1 利用向前 Euler 解 一階常微分方程式
# y' = - y + t +1 , y(0)=1 , 0<= t <= 1
# 取 h=0.02
# 真實解 W(t) = exp(-t) + t
* Forward Euler Method is used for
* solving y'=f(y,t) of first order ordinary differential equation
* with initial condition y(0)=y0 known.
*
'''
import math
def F(y,t):
return ( -y+ t +1 )
def w(t):
return ( math.exp(-t) + t)
#======== main========
t0=0
t1=1
h=0.02
n=int ((t1-t0)/h)
y0= 1
y=y0;
t=t0;
print("t \t\t y(t) \t\t\t w(t) \t\t\t error");
print("=========================================================")
print("{%.2f} \t\t {%10.6f} \t\t {%10.6f} \t\t {%10.6f} " %(t,y,w(t),abs(y-w(t)) ) )
for i in range (1,n+1):
t=t+h
y=y+h*F(y,t)
if (i%10==0):
print("{%.2f} \t\t {%10.6f} \t\t {%10.6f} \t\t {%10.6f} " %(t,y,w(t),abs(y-w(t)) ) )
t y(t) w(t) error
=========================================================
{0.00} { 1.000000} { 1.000000} { 0.000000}
{0.20} { 1.020731} { 1.018731} { 0.002001}
{0.40} { 1.074256} { 1.070320} { 0.003936}
{0.60} { 1.154575} { 1.148812} { 0.005763}
{0.80} { 1.256786} { 1.249329} { 0.007457}
{1.00} { 1.376886} { 1.367879} { 0.009007}
>>>
沒有留言:
張貼留言