Tuesday, February 01, 2011

Demonstration of Euler's Method

The following C program implements Euler’s method for solution of first order differential euation. The initial condition, step size and range over which solution is desired are read as input.        

Source Code:
#include 'stdio.h'
#include 'stdlib.h'
#include 'math.h'

/* Taking the first order differential equation to be dy/dx = -y  */

#define f(x,y) (-y)
#define f1(x,y) (-1)
#define Yn(y) ((1-h)*y)

void main(){

            float x0,xn,x;
            float y0,y,h,ei,eprev;
            int i=1;

            printf(“\n\n        EULER’S METHOD               “);
            printf("\nEnter the initial condition:           ");
            scanf("%f",&y0);
            printf("\nEnter the range of x:   ");
            scanf("%f%f",&x0,&xn);
            printf("\nEnter the step size:   ");
            scanf("%f",&h);

            do{
                        x = x0+h;

                        y = y0+h*f(x0,y0);

                        if(i==1)
                                    ei = fabs((h*h/2)*f1(x0,y0));
                        else
                                    ei = eprev*(1+h*f1(x0,y0));

                        printf("\nAt %dth iteration: \n",i);
                        printf("\tx = %f y = %f e%d = %f",x,y,i,ei);

x0 = x;
y0 = y;
eprev = ei;
i++;

                        }while(x<xn)

            }

Output:
Solving the following differential equation by Euler’s method over the range 0 ≤ x ≤ 2.0 using a step size h = 0.5 with initial condition y(0) = 1. Errors are calculated and printed at each step:



No comments:

Post a Comment

Do you think this information useful or was not up to the mark? Comment if you have any advices or suggestions about the post.