Numerical solution of ordinary differential equations by using Runge-Kutta Method of Order Two and Runge-Kutta Method of Order Four
How to write the C++ codes?
3. TUTORIAL 10 SJEM2231: STRUCTURED PROGRAMMING (C++)
QUESTION 2
Write a C++ function program using RK2 method to solve
= sin(y) ,
with y(0)=1 from x=0 to 0.5 with step size h=0.1.
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
double f(double(x),double(y))
{
return sin(y);
}
int main()
{
long double y[100],x[100], k[100][100];
int n,i;
float h;
cout<<"Enter the value of x0: ";
cin>>x[0];
cout<<"Enter The Value of y0: ";
cin>>y[0];
cout<<"Enter the number of iterations: ";
cin>>n;
cout<<"Enter The Value of Step Size: ";
cin>>h;
4. cout<<"nIterationstxtytK1ttK2"<<endl;
for(i=1;i<=n;i++)
{
k[1][i]= h*f(x[i-1],y[i-1]);
k[2][i]= h*f(x[i-1]+h/2 ,y[i-1]+ (k[1][i])/2);
y[i]=y[i-1]+ k[2][i];
x[i]=x[i-1]+h;
}
for(i=0;i<=n;i++)
{
cout << i <<"tt"<< setprecision(1) << x[i]<<"t";
cout << setprecision(5) << y[i] << "t";
cout << setprecision(3)<< k[1][i] << "tt" << k[2][i] << endl;
}
return 0;
}
//Output:
Enter the value of x0: 0
Enter The Value of y0: 1
Enter the number of iterations: 5
Enter The Value of Step Size: 0.1
Iterations x y K1 K2
0 0 1 0.0841 0.0863
1 0.1 1.0863 0.0885 0.0905
2 0.2 1.1768 0.0923 0.094