2019年5月17日 星期五

C語言 例題5-2用修正Euler尤拉近似法 解一階常微分方程ODE y' = -y+x+1 0<= x <= 1 , y(0)=1 , h=0.2



/* C Program to find approximation of a ordinary
   differential equation using modified Euler's method.
 
    This method is similar to Euler's method ,
    except here we use the average of slopes instead of one.

    x is calculate like the earlier method  and
    y1 = y0 + h*f(x0,y0)
    y2 = y1 +  h*(f(x0,y0)+f(x1,y1))/2
    y3 = y2 +  h*(f(x1,y1)+f(x2,y2))/2
    .
    .
    .
    .
    yn+1 = yn +  h*(f(xn,yn)+f(xn+1,yn+1))/2
    and so on...
*/

#include <stdio.h>
#include <math.h>
#define  w(t)    (exp(-t)+t)

float f(float(x),float(y))
{
    return (-y+x+1);
}


int main()
{
    int n,i;
    float h;
    printf("Given Equation is dy/dx = -y+x+1\n");
    printf("Equation real solution exp(-t)+t \n");
 
    n=5;
    printf("The number of Iterations=%2d\n",n);
    h=0.2;
    printf("Enter The Value of Step Size = %0.4lf\n",h);

    double y[n],x[n],wt[n];
    x[0]=0;
    printf("Enter the value of x0=%0.2lf\n",x[0]);
    y[0]=1;
    printf("Enter The Value of y0=%0.2lf\n",y[0]);

    for(i=1;i<=n;i++)
        x[i]=x[i-1]+h;
 
    for(i=1;i<=n;i++)
    {
        y[i]=y[i-1]+(h*f(x[i-1],y[i-1]));
        y[i]=y[i-1]+(h*(f(x[i-1],y[i-1])+f(x[i],y[i]))/2);
        wt[i]=w(x[i]);
     
    }
 
    printf("\nIterations\t\tx\t\t\ty\t\t\treal\t\terr\n");
    printf("====================================================================\n");
 
    for(i=1;i<=n;i++)
        printf("   %d\t\t\t%0.2lf\t\t%0.4lf\t\t%0.4lf\t\t%0.4lf\n",i,x[i],y[i],wt[i],fabs(y[i]-wt[i]) );
     
    return 0;
}


輸出畫面
Given Equation is dy/dx = -y+x+1
Equation real solution exp(-t)+t
The number of Iterations= 5
Enter The Value of Step Size = 0.2000
Enter the value of x0=0.00
Enter The Value of y0=1.00

Iterations x y real err
===============================
   1 0.20 1.0200 1.0187 0.0013
   2 0.40 1.0724 1.0703 0.0021
   3 0.60 1.1514 1.1488 0.0026
   4 0.80 1.2521 1.2493 0.0028
   5 1.00 1.3707 1.3679 0.0029

沒有留言:

張貼留言

Messaging API作為替代方案

  LINE超好用功能要沒了!LINE Notify明年3月底終止服務,有什麼替代方案? LINE Notify將於2025年3月31日結束服務,官方建議改用Messaging API作為替代方案。 //CHANNEL_ACCESS_TOKEN = 'Messaging ...