- First order Differential equations
- Higher Order Differential equations
- Euler method
- Predictor corrector method
- Runge Kutta method
Let us look at Euler method, in this we divide difference between intial value of X and final value of X into n intervals, calling it h.
Y' = Y+X Initial values Y(1)=2, Find value of Y(2)
Now x_initial = 1 and x_final = 2 , h = x_final-x_initial/n
at n =5 h= .2
Y(1.2) = Y(1)+ (0.2)*(Y(1)+X(1)) = 2.6
Y(1.4) = Y(1.2) + (0.2)*(Y(1.2) + X(1.2)) = 2.6+ .2* (2.6 + 1.2) = 3.36
and continue.
C++ Code for Euler method
I have developed code for the implementation of Euler method in c++, Please find it below (hope commenting is enough for understanding)
#include // for normal_distribution
using boost::math::normal; // typedef provides default type is double.
#include
using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;
#include
using std::setw; using std::setprecision;
#include
using std::numeric_limits;
#include
#include
using namespace std;
int main()
{
float y_initial,y_final;
float x_initial,x_final;
float derv_y,derv_x,c_const;
float count,h;
int i;
//open file to store results
std::ofstream myfile;
myfile.open("plota.data");
// warning to enter 0 if variable has no value
cout<<"\n Enter 0 if variable has no valuee"<
// Get all the X and Y values
cout << "\n Enter intial value of X and Y respectively"<
cin>>x_initial>>y_initial;
//Taking final value of X where we need to calculate Y
cout << "\n Final value of X"<
cin>>x_final;
// Get Count of interval
cout<<"\n Number of Interval Required"<
cin>>count;
// Coeffciient of derivative equations
cout<<" \n Enter the coefficient of Y, X and constant of derivative"<
cin>>derv_y>>derv_x>>c_const;
//Calculating intervals
h= ( x_final - x_initial ) / count;
//Loop to find values
for(i =0;i
{
y_final = y_initial + h * (derv_y*y_initial+derv_x*x_initial+c_const);
y_initial = y_final;
x_initial = x_initial+h;
myfile<
}
return 0;
}
Output of the code-
Enter 0 if variable has no valuee
Enter intial value of X and Y respectively
1
2
Final value of X
2
Number of Interval Required
10
Enter the coefficient of Y, X and constant of derivative
1
1
0
The result is stored in "plota.data" file and can plotted using GNU plot, Run following commands
gnuplot> set terminal postscript
Terminal type set to 'postscript'
Options are 'landscape noenhanced defaultplex \
leveldefault monochrome colortext \
dashed dashlength 1.0 linewidth 1.0 butt noclip \
palfuncparam 2000,0.003 \
"Helvetica" 14 '
gnuplot> set output "ODE.ps"
gnuplot> plot "plota.data"
result looks like below
No comments:
Post a Comment