C++ Program for Euler’s Method to solve an ODE(Ordinary Differential Equation)

//Eulers Method to solve a differential equation
using namespace std;
double df(double x, double y)            //function for defining dy/dx
    double a=x+y;                //dy/dx=x+y
    return a;
int main()
    int n;   
    double x0,y0,x,y,h;            //for initial values, width, etc.
    cout.precision(5);            //for precision
    cout<<"\nEnter the initial values of x and y respectively:\n";        //Initial values
    cout<<"\nFor what value of x do you want to find the value of y\n";   
    cout<<"\nEnter the width of the sub-interval:\n";            //input width
    while(fabs(x-x0)>0.0000001)        //I couldn't just write "while(x0<x)" as they both are floating point nos. It is dangerous to compare two floating point nos. as they are not the same in binary as they are in decimal. For instance, a computer cannot exactly represent 0.1 or 0.7 in binary just like decimal can't represent 1/3 exactly without recurring digits.
        y=y0+(h*df(x0,y0));            //calculate new y, which is y0+h*dy/dx   
        y0=y;                    //pass this new y as y0 in the next iteration.
        x0=x0+h;                //calculate new x.
    cout<<"The approximate value of y at x=0 is "<<y<<endl;        //print the solution.
    return 0;

For dy/dx=-2x-y
euler 2 output
For dy/dx=x+y

Explanation of the Code:

Leave a Reply

Your email address will not be published. Required fields are marked *