2019年1月23日 星期三

例題 5-5 利用 二階 Runge-Kutta 解一階常微分方程式 y' = - y + t^2 +1 , y(0)=1 , 0<= t <= 1 取 h=0.01 真實解 W(t) = -2 exp(-t) + t^2 - 2t +3


'''
#例題 5-5 利用 二階 Runge-Kutta  解一階常微分方程式
# y' = - y + t^2  +1  , y(0)=1  , 0<= t <= 1
# 取 h=0.01
# 真實解 W(t) =  -2 exp(-t)  + t^2 - 2t +3

 * 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*t+1)
def W(t):
    return (-2*(1.0/math.exp(t))+pow(t,2)-2*t+3)


#======== main========
n=100;
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) \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
    if(i%10==0):
        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-5.py ============
    t y(t)                 w(t)                 error
=========================================================
{0.00}   { 1.0000000}    { 1.0000000} { 0.0000000} 
{0.10}   { 1.0003269}    { 1.0003252} { 0.0000017} 
{0.20}   { 1.0025421}    { 1.0025385} { 0.0000036} 
{0.30}   { 1.0083691}    { 1.0083636} { 0.0000056} 
{0.40}   { 1.0193675}    { 1.0193599} { 0.0000076} 
{0.50}   { 1.0369483}    { 1.0369387} { 0.0000096} 
{0.60}   { 1.0623883}    { 1.0623767} { 0.0000116} 
{0.70}   { 1.0968430}    { 1.0968294} { 0.0000136} 
{0.80}   { 1.1413577}    { 1.1413421} { 0.0000156} 
{0.90}   { 1.1968782}    { 1.1968607} { 0.0000175} 
{1.00}   { 1.2642605}    { 1.2642411} { 0.0000194} 
>>> 

沒有留言:

張貼留言

Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3

  Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3 AngularJS 實例 <!DOCTYPE html> <html> <head> <meta charse...