Euler Method is a Numerical technique used to solve ordinary differential equations.
In this post I will show you how to write a C program to find the solution of a first order differential equation using the Euler’s Method.
Let’s say we have a differential equation
One can easily see that, is the solution.
Now if we have some initial values for the function, like if we are given , then we know that the constant of integration
.
Using this we can now calculate the value of y for any given x.
This is what we would like to achieve from our program. We cannot have our program tell us the analytical form of y, but we can approximate the value of y for a given x, using the Euler’s Method.
In Euler’s Method, we ask the user to give us the initial values for x and y.
Let’s call these and
.
Then we find out the slope of at
, using the differential equation
.
Then we use this slope to find the value of at
. So basically we approximate the function using a line. Therefore, for better accuracy the value of
should be very small.
We keep on incrementing x and approximating y until we reach the x value for which y is desired.
Algorithm:
- Enter the initial values of
and
(xi and yi respectively).
- Enter the value of
, for which
is to be determined.
- Enter the width of the interval, ‘
’.
- Do:
y=y0+(h*dy/dx(xi,yi))
yi=y.
xi=xi+h
Until (xi>=x) - Print y, which is the solution.
PROGRAM:
/*********************************************** ****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 -2*x-y; } main(){ int i; double y,xi,yi,xf,h; printf("Enter the initial condition for y: "); scanf("%lf",&yi); printf("Enter the initial condition for x: "); scanf("%lf",&xi); printf("Enter the value of x for which y is required: "); scanf("%lf",&xf); printf("Enter the step-width h: "); scanf("%lf",&h); printf("x\t\ty\t\ty'\t\thy'\t\ty+hy'\n"); printf("__________________________________________________________________________\n"); //Begin Euler Routine while(xi<xf){ y=yi+h*f(xi,yi); printf("%lf\t%lf\t%lf\t%lf\t%lf\n",xi,yi,f(xi,yi),h*f(xi,yi),y); yi=y; xi=xi+h; } printf("%lf\t%lf\n",xi,yi); printf("__________________________________________________________________________\n"); printf("The value of y is %lf\n\n",y); }
OUTPUT:
REFERENCES:
http://tutorial.math.lamar.edu/Classes/DE/EulersMethod.aspx
It was really a previledge for me to see this. I learnt a lot from it. May God increase your strength sir