thespeedracer38

Second Order Runge Kutta Method

Feb 14th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using namespace std;
  5.  
  6. class RungeSecondOrder{
  7.         double x0, y0, h, no_of_intervals;
  8.     public:
  9.         RungeSecondOrder(double = 0, double = 0, double = 0, int = 0);
  10.         double f(double, double);
  11.         double calcY(double, double);
  12.         double displayAll();
  13. };
  14.  
  15. inline double RungeSecondOrder::f(double x, double y){
  16.     return y + (0 * x);
  17. }
  18.  
  19. inline RungeSecondOrder::RungeSecondOrder(double h, double x0, double y0, int no_of_intervals){
  20.     RungeSecondOrder::h = h;
  21.     RungeSecondOrder::x0 = x0;
  22.     RungeSecondOrder::y0 = y0;
  23.     RungeSecondOrder::no_of_intervals = no_of_intervals;
  24. }
  25.  
  26. inline double RungeSecondOrder::calcY(double x, double y){
  27.     double k1 = h * f(x, y);
  28.     double k2 = h * f(x + h, y + h);
  29.     return y + (.5 * (k1 + k2));
  30. }
  31.  
  32. double RungeSecondOrder::displayAll(){
  33.     double curr_x = x0, curr_y = y0;
  34.     cout << "x = " << curr_x << " y = " << curr_y << endl;
  35.     for(double i = 1; i <= no_of_intervals; i++){
  36.         curr_y = calcY(curr_x, curr_y);
  37.         curr_x += h;
  38.         cout << "x = " << curr_x << " y = " << curr_y << endl;
  39.     }
  40. }
  41.  
  42. int main() {
  43.     system("cls");
  44.     double x0, y0, h, no_of_intervals;
  45.     cout << "Enter x0 = ";
  46.     cin >> x0;
  47.     cout << "Enter y0 = ";
  48.     cin >> y0;
  49.     cout << "Enter h = ";
  50.     cin >> h;
  51.     cout << "Enter number of intervals = ";
  52.     cin >> no_of_intervals;
  53.     RungeSecondOrder obj(h, x0, y0, no_of_intervals);
  54.     obj.displayAll();
  55.     cin.ignore();
  56.     cin.get();
  57.     return 0;
  58. }
Add Comment
Please, Sign In to add comment