HaS5HeM

RK4 Algorithm using Modern C++

Dec 27th, 2021 (edited)
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. float h, X0, Y0, N, k{ 0.0009906f };
  5.  
  6. float diff_Fun(float x, float y = 0) {
  7.     return k * y * (1000.0f - y);
  8. }
  9.  
  10. float k1(float x, float y = 0) {
  11.     return h * diff_Fun(x, y);
  12. }
  13.  
  14. float k2(float x, float y = 0) {
  15.     return h * diff_Fun(x + 0.5f * h, y + 0.5f * k1(x, y));
  16. }
  17.  
  18. float k3(float x, float y = 0) {
  19.     return h * diff_Fun(x + 0.5f * h, y + 0.5f * k2(x, y));
  20. }
  21.  
  22. float k4(float x, float y = 0) {
  23.     return h * diff_Fun(x + h, y + k3(x, y));
  24. }
  25.  
  26. int main() {
  27.     cout << "Enter the number of mesh points, x0, and Y(x0)" << endl;
  28.     cin >> N >> X0 >> Y0; h = 7 / N;
  29.  
  30.     float* time_points = new float[N + 1] { 0 };
  31.     float* Y_F = new float[N + 1] { 0 };
  32.  
  33.     Y_F[0] = Y0;
  34.     time_points[0] = X0;
  35.  
  36.     for (int i = 1; i < N; i++) {
  37.         Y_F[i] = Y_F[i - 1] + (1.0f / 6.0f) * (k1(time_points[i - 1], Y_F[i - 1]) + 2.0f * k2(time_points[i - 1], Y_F[i - 1]) + 2.0f * k3(time_points[i - 1], Y_F[i - 1]) + k4(time_points[i - 1], Y_F[i - 1]));
  38.         cout << Y_F[i] << "\t" << i << endl;
  39.         time_points[i] = time_points[i - 1] + h;
  40.     }
  41.  
  42.     return 0;
  43. }
Add Comment
Please, Sign In to add comment