Advertisement
shakhawatt

RK

Dec 26th, 2021
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. // C++ program to implement Runge
  2. // Kutta method
  3. #include <bits/stdc++.h>
  4.  
  5. using namespace std;
  6.  
  7. // A sample differential equation
  8. // "dy/dx = (x - y)/2"
  9.  
  10. float dydx(float x, float y)
  11. {
  12.  
  13. return (x + y - 2);
  14. }
  15.  
  16. // Finds value of y for a given x
  17. // using step size h
  18. // and initial value y0 at x0.
  19.  
  20. float rungeKutta(float x0, float y0,
  21.  
  22. float x, float h)
  23. {
  24.  
  25. // Count number of iterations
  26.  
  27. // using step size or
  28.  
  29. // step height h
  30.  
  31. int n = (int)((x - x0) / h);
  32.  
  33.  
  34. float k1, k2;
  35.  
  36.  
  37. // Iterate for number of iterations
  38.  
  39. float y = y0;
  40.  
  41. for (int i = 1; i <= n; i++)
  42. {
  43.  
  44. // Apply Runge Kutta Formulas
  45.  
  46. // to find next value of y
  47.  
  48. k1 = h * dydx(x0, y);
  49.  
  50. k2 = h * dydx(x0 + 0.5 * h,
  51.  
  52. y + 0.5 * k1);
  53.  
  54.  
  55. // Update next value of y
  56.  
  57. y = y + (1.0 / 6.0) * (k1 + 2 * k2);
  58.  
  59.  
  60. // Update next value of x
  61.  
  62. x0 = x0 + h;
  63.  
  64. }
  65.  
  66.  
  67. return y;
  68. }
  69.  
  70. // Driver Code
  71.  
  72. int main()
  73. {
  74.  
  75. float x0 = 0, y = 1,
  76.  
  77. x = 2, h = 0.2;
  78.  
  79.  
  80. cout << fixed << setprecision(6) << "y(x) = " << rungeKutta(x0, y, x, h);
  81.  
  82. return 0;
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement