2019年1月3日 星期四

範例EX5-1 利用向前Euler尤拉近似法 解一階常微分方程ODE ----C語言

範例EX5-1
利用向前Euler尤拉近似法 解一階常微分方程ODE
y' = -y + t +1 , 0<= t <= 1 , y(0)=1 , h=0.2

真實解= e^(-t) + t

C語言程式:
/* ex5-1.c Forward Euler Method is used for
 * solving y'=f(y,t) of first order
 * ordinary differential equation
 * with initial condition y(0)=y0
 * known.
 */
#include <stdio.h>
#include <math.h>
#define  F(y,t)   (-y+t+1)         //y' = -y + t +1
#define  w(t)   (exp(-t)+t)  //真實解
void main()
{
   int i,n=5;
   double h=0.2,y,t,y0=1,t0=0;
   y=y0;
   t=t0;
   printf("t         y(t)         w(t)        error\n");
   printf("========================================\n");
   printf("%.2lf  %10.6lf  %10.6lf  %10.6lf\n",
   t,y,w(t),fabs(y-w(t)));
   for(i=1;i<=n;i++)
   {
      y=y+h*F(y,t);
      t=t+h;
      //if(i%5==0)
      printf("%.2lf  %10.6lf  %10.6lf  %10.6lf\n",
        t,y,w(t),fabs(y-w(t)));

   }
   return;
}

t         y(t)         w(t)        error                                                                                                                      
========================================                                                                                                                      
0.00    1.000000    1.000000    0.000000                                                                                                                      
0.20    1.000000    1.018731    0.018731                                                                                                                      
0.40    1.040000    1.070320    0.030320                                                                                                                      
0.60    1.112000    1.148812    0.036812                                                                                                                      
0.80    1.209600    1.249329    0.039729                                                                                                                      
1.00    1.327680    1.367879    0.040199                                                                                                                      
                                                                                                                                                              
                                                                                                                                                              
...Program finished with exit code 41                                                                                                                         

沒有留言:

張貼留言

WOKWI LED + MQTT Node-Red SQLite

WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...