TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
rungekutta.cpp
Go to the documentation of this file.
1
21#include <cassert>
22#include <cstdint>
23#include <iostream>
24#include <vector>
33static double change(double x, double y) { return ((x - y) / 2.0); }
34
39namespace numerical_methods {
45namespace runge_kutta {
57double rungeKutta(double init_x, const double &init_y, const double &x,
58 const double &h) {
59 // Count number of iterations
60 // using step size or
61 // step height h
62
63 // n calucates the number of iterations
64 // k1, k2, k3, k4 are the Runge Kutta variables
65 // used for calculation of y at each iteration
66
67 auto n = static_cast<uint64_t>((x - init_x) / h);
68 // used a vector container for the variables
69 std::vector<double> k(4, 0.0);
70
71 // Iterate for number of iterations
72
73 double y = init_y;
74 for (int i = 1; i <= n; ++i) {
75 // Apply Runge Kutta Formulas
76 // to find next value of y
77 k[0] = h * change(init_x, y);
78 k[1] = h * change(init_x + 0.5 * h, y + 0.5 * k[0]);
79 k[2] = h * change(init_x + 0.5 * h, y + 0.5 * k[1]);
80 k[3] = h * change(init_x + h, y + k[2]);
81
82 // Update next value of y
83
84 y += (1.0 / 6.0) * (k[0] + 2 * k[1] + 2 * k[2] + k[3]);
85
86 // Update next value of x
87
88 init_x += h;
89 }
90
91 return y;
92}
93} // namespace runge_kutta
94} // namespace numerical_methods
95
100static void test() {
101 std::cout << "The Runge Kutta function will be tested on the basis of "
102 "precomputed values\n";
103
104 std::cout << "Test 1...."
105 << "\n";
106 double valfirst = numerical_methods::runge_kutta::rungeKutta(
107 2, 3, 4, 0.2); // Tests the function with pre calculated values
108 assert(valfirst == 3.10363932323749570);
109 std::cout << "Passed Test 1\n";
110
111 std::cout << "Test 2...."
112 << "\n";
113 double valsec = numerical_methods::runge_kutta::rungeKutta(
114 1, 2, 5, 0.1); // The value of step changed
115 assert(valsec == 3.40600589380261409);
116 std::cout << "Passed Test 2\n";
117
118 std::cout << "Test 3...."
119 << "\n";
120 double valthird = numerical_methods::runge_kutta::rungeKutta(
121 -1, 3, 4, 0.1); // Tested with negative value
122 assert(valthird == 2.49251005860244268);
123 std::cout << "Passed Test 3\n";
124}
125
130int main() {
131 test(); // Execute the tests
132 return 0;
133}
int h(int key)
Functions for Runge Kutta fourth order method.
static double change(double x, double y)
asserting the test functions
double rungeKutta(double init_x, const double &init_y, const double &x, const double &h)
the Runge Kutta method finds the value of integration of a function in the given limits....
static void test()
Tests to check algorithm implementation.
int main()
Main function.