Eulers Method Implementation in C programming

A differential equation (D.E.) of the form dy/dx= f (x, y) and an initial condition (x0,y0), we would like to a find function y = f (x) that satisfies the D.E. and passes through the point (x0,y0). In some cases, one can identify the general solution to the D.E. by inspection or using methods such as separation of variables and integration. But sometimes, either we don’t have the analytic tools in our tool bag to solve the D.E. or an analytic solution is not possible. That’s when we need a numerical method for solving the D.E. One such method is Euler’s Method.

In computational science and numerical analysis, the Euler method is a first-order numerical procedure for solving ordinary differential equations with a given initial value.
In order to use Euler's Method to generate a numerical solution to an initial value problem of the form:


We decide upon what interval, starting at the initial condition, we desire to find the solution. We chop this interval into small subdivisions of length h. Then, using the initial condition as our starting point, we generate the rest of the solution by using the iterative formulas:




 where,

To find the coordinates of the points in our numerical solution. We terminate this process when we have reached the right end of the desired interval.

Implementing Euler method in C:

#include<stdio.h>
#include <math.h>
#include<conio.h>
#define F(x,y)  (x*x+y)       /* here we can change our function according to problem*/
void main()
{
  double y0,y1,x0,a,n,h;
  int j;
  printf("\nEnter the value of range: ");
  scanf("%lf %lf",&a,&n);
  printf("\nEnter the value of y0: ");
  scanf("%lf",&y0);
  printf("\n\nEnter the h: ");
  scanf("%lf",&h);
  printf("\n\n  y0 = %.3lf ",y0);
 for (x0=a,j=1; x0<=n+h; x0=x0+h,j++)
  {
   y1= y0 + h * F(x0,y0);
   printf("\n\n  x = %.3lf  ",x0);
   printf("\n\n  y%d = %.3lf",j,y1);
   y0=y1;
  }
getch();
}

Output:

Euler’s method is a relatively simple method for approximating solutions to differential equations numerically. It is not generally used, Because the method takes too much work for too little of a result. It is considered to be very slow. Much more sophisticated algorithms exist for approximating solutions to differential equations which are generally based on the ideas in Euler’s method.

0/Post a Comment/Comments