龙格-库塔四阶常微分方程法则


龙格-库塔法用于求解常微分方程 (ODE),它使用 x 和 y 求 dy/dx 函数,还需要 y 的初值,即 y(0)。它求解给定 x 近似 y 的值。要求解 ODE,我们必须遵循以下公式

其中 h 是区间的长度。

注意:从这些公式中,我们可以使用前两个 k1 和 k2 找到 ODE 的龙格-库塔二阶解。

输入和输出

Input:
The x0 and f(x0): 0 and 0
the value of x = 0.4
the value of h = 0.1
Output:
Answer of differential equation: 0.0213594

算法

rungeKutta(x0, y0, x, h)

输入 − 初始 x 和 y 值,目标 x 值和区间长度 h。

输出 − 值 x 的 y 值。

Begin
   iteration := (x – x0)/h
   y = y0
   for i := 1 to iteration, do
      k1 := h*f(x0, y)
      k2 := h*f((x0 + h/2), (y + k1/2))
      k3 := h*f((x0 + h/2), (y + k2/2))
      k4 := h*f((x0 + h), (y + k3))
      y := y + (1/6)*(k1 + 2k2 + 2k3 + k4)
      x0 := x0 + h
   done
   return y
End

示例

#include <iostream>
using namespace std;

double diffOfy(double x, double y) {
   return ((x*x)+(y*y)); //function x^2 + y^2
}

double rk4thOrder(double x0, double y0, double x, double h) {
   int iteration = int((x - x0)/h);    //calculate number of iterations
   double k1, k2, k3, k4;
   double y = y0;    //initially y is f(x0)

   for(int i = 1; i<=iteration; i++) {
      k1 = h*diffOfy(x0, y);
      k2 = h*diffOfy((x0+h/2), (y+k1/2));
      k3 = h*diffOfy((x0+h/2), (y+k2/2));
      k4 = h*diffOfy((x0+h), (y+k3));
         
      y += double((1.0/6.0)*(k1+2*k2+2*k3+k4));    //update y using del y
      x0 += h;    //update x0 by h
   }
   return y;    //f(x) value
}

int main() {
   double x0, y0, x, h;
   cout << "Enter x0 and f(x0): "; cin >> x0 >> y0;
   cout << "Enter x: "; cin >> x;
   cout << "Enter h: "; cin >> h;
   cout << "Answer of differential equation: " << rk4thOrder(x0, y0, x, h);
}

输出

Enter x0 and f(x0): 0 0
Enter x: 0.4
Enter h: 0.1
Answer of differential equation: 0.0213594

更新时间: 17-6-2020

2K+ 次访问

开启你的 职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.