Euler's Method C++ Program For Solving Ordinary Differential Equation
This program is implementation of Euler's method for solving ordinary differential equation using C++ programming language with output.
Output of this is program is solution for dy/dx = x + y with initial condition y = 1 for x = 0 i.e. y(0) = 1 and we are trying to evaluate this differential equation at y = 0.5. ( Here y = 1 i.e. y(0.5) = ? is our calculation point)
C++ Program for Euler's Method
#include<iostream>
/* defining ordinary differential equation to be solved */
/* In this example we are solving dy/dx = x + y */
#define f(x,y) x+y
using namespace std;
int main()
{
float x0, y0, xn, h, yn, slope;
int i, n;
cout<<"Enter Initial Condition"<< endl;
cout<<"x0 = ";
cin>> x0;
cout<<"y0 = ";
cin >> y0;
cout<<"Enter calculation point xn = ";
cin>>xn;
cout<<"Enter number of steps: ";
cin>> n;
/* Calculating step size (h) */
h = (xn-x0)/n;
/* Euler's Method */
cout<<"\nx0\ty0\tslope\tyn\n";
cout<<"------------------------------\n";
for(i=0; i < n; i++)
{
slope = f(x0, y0);
yn = y0 + h * slope;
cout<< x0<<"\t"<< y0<<"\t"<< slope<<"\t"<< yn<< endl;
y0 = yn;
x0 = x0+h;
}
/* Displaying result */
cout<<"\nValue of y at x = "<< xn<< " is " << yn;
return 0;
}
Euler's Method C++ Program Output
Enter Initial Condition x0 = 0 y0 = 1 Enter calculation point xn = 0.5 Enter number of steps: 10 x0 y0 slope yn ------------------------------ 0.000 1.000 1.000 1.050 0.050 1.050 1.100 1.105 0.100 1.105 1.205 1.165 0.150 1.165 1.315 1.231 0.200 1.231 1.431 1.303 0.250 1.303 1.553 1.380 0.300 1.380 1.680 1.464 0.350 1.464 1.814 1.555 0.400 1.555 1.955 1.653 0.450 1.653 2.103 1.758 Value of y at x = 0.500 is 1.758
Recommended Readings
- Ordinary Differential Equation Using Euler's Method Algorithm
- Ordinary Differential Equation Using Euler's Method Pseudocode
- Ordinary Differential Equation Using Euler's Method Using C Programming
- Ordinary Differential Equation Using Euler's Method Using C++ Programming
- Ordinary Differential Equation Using Fourth Order Runge Kutta (RK) Method Algorithm
- Ordinary Differential Equation Using Fourth Order Runge Kutta (RK) Method Pseudocode
- Ordinary Differential Equation Using Fourth Order Runge Kutta (RK) Method Using C
- Runge Kutta (RK) Fourth Order Using C++ with Output