Runge Kutta (RK) Fourth Order Using C++ with Output


Implementation of Runge Kutta (RK) Fourth Order method for solving ordinary differential equation using C++ programming language with output is given below.

Output of this is program is solution for dy/dx = (y2 - x2)/(y2+x2) 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.6 in three steps i.e. n = 3. ( Here y = 0.6 i.e. y(0.6) = ? is our calculation point)

C++ Program for RK-4 Method


#include<iostream>

/* Defining ordinary differential equation to be solved */
#define f(x,y) (y*y-x*x)/(y*y+x*x)

using namespace std;

#include

/* defining ordinary differential equation to be solved */
#define f(x,y) (y*y-x*x)/(y*y+x*x)

using namespace std;
int main()
{
 float x0, y0, xn, h, yn, k1, k2, k3, k4, k;
 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;

 /* Runge Kutta Method */
 cout<<"\nx0\ty0\tyn\n";
 cout<<"------------------\n";
 for(i=0; i < n; i++)
 {
  k1 = h * (f(x0, y0));
  k2 = h * (f((x0+h/2), (y0+k1/2)));
  k3 = h * (f((x0+h/2), (y0+k2/2)));
  k4 = h * (f((x0+h), (y0+k3)));
  k = (k1+2*k2+2*k3+k4)/6;
  yn = y0 + k;
  cout<< x0<<"\t"<< y0<<"\t"<< yn<< endl;
  x0 = x0+h;
  y0 = yn;
 }

 /* Displaying result */
 cout<<"\nValue of y at x = "<< xn<< " is " << yn;

 return 0;
}


RK-4 C++ Program Output

	
Enter Initial Condition
x0 = 0
y0 = 1
Enter calculation point xn = 0.6
Enter number of steps: 3

x0      y0      yn
------------------
0       1       1.196
0.2     1.196   1.37527
0.4     1.37527 1.53311

Value of y at x = 0.6 is 1.53311
	

Recommended Readings

  1. Ordinary Differential Equation Using Euler's Method Algorithm
  2. Ordinary Differential Equation Using Euler's Method Pseudocode
  3. Ordinary Differential Equation Using Euler's Method Using C Programming
  4. Ordinary Differential Equation Using Euler's Method Using C++ Programming
  5. Ordinary Differential Equation Using Fourth Order Runge Kutta (RK) Method Algorithm
  6. Ordinary Differential Equation Using Fourth Order Runge Kutta (RK) Method Pseudocode
  7. Ordinary Differential Equation Using Fourth Order Runge Kutta (RK) Method Using C
  8. Runge Kutta (RK) Fourth Order Using C++ with Output