2019年5月12日 星期日

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

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

/***********************************************
****EULER METHOD FOR DIFFERENTIAL EQUATIONS*****
***********************************************/
#include<stdio.h>
#include<math.h>
/*Define the RHS of the first order differential equation here(Ex: dy/dx=f(x,y))  */
double f(double x, double y){
return -y+x+1;
}

double predict(double x, double y, double h)
{
    // value of next y(predicted) is returned
    double y1p = y + h * f(x, y);
    return y1p;
}


// using Modified Euler method
double correct(double x, double y, double x1, double y1,double h)
{
    // (x, y) are of previous step
    // and x1 is the increased x for next step
    // and y1 is predicted y for next step
    double e = 0.00001;
    double y1c = y1;

    do {
        y1 = y1c;
        y1c = y + 0.5 * h * (f(x, y) + f(x1, y1));
    } while (fabs(y1c - y1) > e);

    // every iteration is correcting the value
    // of y using average slope
    return y1c;
}



int main()
{
    // here x and y are the initial
    // given condition, so x=0 and y=15
    double x = 0, y = 1;

    // final value of x for which y is needed
    double xn = 1;

    // step size
    double h = 0.2;
    int i=1;
        while (x < xn) {
            double x1 = x + h;
            double y1p = predict(x, y, h);
            double y1c = correct(x, y, x1, y1p, h);
            printf("Euler Modified method----The value of y , at x = %2.2lf is :%2.4lf\n" ,x1 ,y1c);
            x = x1;
            y = y1c;
            i++;
    }

return 0;
}


輸出畫面
Euler Modified method----The value of y , at x = 0.20 is :1.0182
Euler Modified method----The value of y , at x = 0.40 is :1.0694
Euler Modified method----The value of y , at x = 0.60 is :1.1477
Euler Modified method----The value of y , at x = 0.80 is :1.2481
Euler Modified method----The value of y , at x = 1.00 is :1.3666

沒有留言:

張貼留言

Messaging API作為替代方案

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