Advertisement
gashink_t

Untitled

Oct 20th, 2021
995
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <memory>
  4. #include <iomanip>
  5. using namespace std;
  6. float a = 0, b = 10; //левая и правая границы (a и b)
  7. float h = 0.1; //шаг
  8. const float n = ((b - a)/h + 1); //кол-во решений
  9.  
  10. /*Наша функция*/
  11. float df(float x, float y) {
  12.     return x + y;
  13. }
  14.  
  15. void Runge(float a, float b);
  16. void print(float* X, float* Y);
  17.  
  18. int main() {
  19.     Runge(a, b);
  20.     return 0;
  21. }
  22.  
  23. /*Метод Рунге-Кутта*/
  24. void Runge(float a, float b)
  25. {  
  26.     float* X = new float[n];
  27.     float* Y = new float[n];
  28.     X[0] = a; ;//присваиваем X[0] значение левой границы
  29.     Y[0] = 1; //присваиваем Y[0] значение 1
  30.     float k1, k2, k3, k4; //для ДУ 4-го порядка
  31.  
  32.     for (int i = 1; i < n; i++)
  33.     {
  34.         k1 = h * df(X[i - 1], Y[i - 1]);
  35.         k2 = h * df(X[i - 1] + h / 2, Y[i - 1] + k1 / 2);
  36.         k3 = h * df(X[i - 1] + h / 2, Y[i - 1] + k2 / 2);
  37.         k4 = h * df(X[i - 1] + h, Y[i - 1] + k3);
  38.         X[i] = a + i * h;
  39.         Y[i] = Y[i - 1] + (k1 + 2*k2 + 2*k3 + k4) / 6;
  40.     }
  41.  
  42.     print(X, Y);
  43. }
  44.  
  45. void print(float* X, float* Y)
  46. {
  47.     cout << "Table Runge:\n";
  48.     for (int i = 0; i < n; i++) {
  49.         if (i == 0 || i == n - 1) cout << "X[" << i << "]=" << X[i] << "\t\tY[" << i << "]=" << Y[i] << endl;
  50.         else cout << "X[" << i << "]=" << X[i] << "\tY[" << i << "]=" << fixed << setprecision(4) << Y[i] << endl;
  51.     }
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement