'''
#例題 5-4 利用 二階 Runge-Kutta 解一階常微分方程式
# y' = - y + t +1 , y(0)=1 , 0<= t <= 1
# 取 h=0.2
# 真實解 W(t) = exp(-t) + t
* Second Order Runge-Kutta 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========
n=5;
a=0.0
b=1.0
y0=1.0
h=(b-a)/n
y=y0
t0=a
t=t0
print("t \t\t y(t) \t\t\t w(t)=exp(-t)+t \t\t error");
print("=========================================================")
print("{%.2f} \t\t {%10.7f} \t\t {%10.7f} \t\t {%10.7f} " %(t,y,W(t),abs(y-W(t)) ) )
for i in range (1,n+1):
k1=h*F(y,t)
k2=h*F((y+k1),(t+h))
y=y+0.5*(k1+k2)
t=t+h
#print(t,W(t))
print("{%.2f} \t\t {%10.7f} \t\t {%10.7f} \t\t {%10.7f} " %(t,y,W(t),abs(y-W(t)) ) )
========= RESTART: F:/2018-09勤益科大數值分析/數值分析/PYTHON/EX5-4.py ============
t y(t) w(t)=exp(-t)+t error
=========================================================
{0.00} { 1.0000000} { 1.0000000} { 0.0000000}
{0.20} { 1.0200000} { 1.0187308} { 0.0012692}
{0.40} { 1.0724000} { 1.0703200} { 0.0020800}
{0.60} { 1.1513680} { 1.1488116} { 0.0025564}
{0.80} { 1.2521218} { 1.2493290} { 0.0027928}
{1.00} { 1.3707398} { 1.3678794} { 0.0028604}
>>>
沒有留言:
張貼留言