如何在 C++ 中使用 RK4 求解这个微分方程?

计算科学 C++
2021-12-30 06:22:25

我得到了以下作业问题来解决:

方程的图像

我在用 C++ 为这个 ODE 编写 RK4 求解器时遇到了麻烦。我也不确定如何绘制我的解决方案。到目前为止,这是我的代码:

#include <iostream> //Header file for cin & cout
#include <cmath>    //Header file for mathematical operartions
#include <iomanip>  //Header file for precession
#include <fstream>
#include <string>
using namespace std; //calling the standard directory
float F(float y, float x)
{ return 0; }


int main()
{
  float y0,x0,z0,y1, z1,n,h,f,k1,k2,k3,k4, j1, j2, j3, j4;
  cout<<"\nEnter the value of x0 (initial value): "; //Entering the initial values of x & y
  cin>>x0;
  cout<<"\nEnter the value of y0 (initial value): ";
  cin>>y0;
  cout<<"\nEnter the value of z : ";
  cin>>z0;
  cout<<"\nEnter the value of h (step size): ";//Entering the width of step size
  cin>>h;
  cout<<"\nEnter the value of last point of x: ";
  cin>>n;
  cout<<"\nStart point (x,y) : "<<x0<<", "<<y0<<endl;

  for( ; x0<n; x0=x0+h){
    f=F(x0,y0);
    k1 = h * f;
    f = F(x0+h/2,y0+k1/2);
    k2 = h * f;
    f = F(x0+h/2,y0+k2/2);
    k3 = h * f;
    f = F(x0+h/2,y0+k2/2);
    k4 = h * f;

    k1=z0;
    j1=-x0*y0;
    k2=z0+(0.5)*j1;
    j2=-(x0+(0.5)*h)*(y0+(0.5)*k1);
    k3=z0+(0.5)*j2;
    j3=-(x0+(0.5)*h)*(y0+(0.5)*k2);
    k4=z0+j3;
    j4=-(x0+h)*(y0+k3);

    y1=y0+(h/6)*(k1+2*(k2)+2*(k3)+k4);
    z1=z0+(h/6)*(j1+2*(j2)+2*(j3)+j4);

    cout<<"\n k1 = "<<k1;
    cout<<"\n k2 = "<<k2;
    cout<<"\n k3 = "<<k3;
    cout<<"\n k4 = "<<k4;
    cout<<"\n j1 = "<<j1;
    cout<<"\n j2 = "<<j2;
    cout<<"\n j3 = "<<j3;
    cout<<"\n j4 = "<<j4<<endl;
    cout<<"\n x = "<<x0+h<<" and y = "<<y1<<endl;
    y0=y1; //take new point for next calculation
  }
}
1个回答

这看起来像是要求您根据时间绘制电流。我会推荐你​​使用 MATLAB,因为它内置了 4 阶 RK 方法的求解器,因此你不需要编写自己的代码。在 MATLAB 中绘图也非常简单和干净。

在我的一项作业中,我在 MATLAB 中求解了一个名为 Falkner Skan Flow Equation 的方程,尽管我编写了自己的代码,就像您在 C++ 中所做的那样。你可以在这里找到我的代码http://www.mathworks.com/matlabcentral/fileexchange/50460-falkner-skan-solution--without-using-ode45--fundamental-program

在同一个名为 MATLAB File Exchange 的网站上,您可以找到其他代码,这些代码可以帮助您理解 RK 方法及其在微分方程中的应用。如果您坚持使用 C++,您可以在我的代码中看到算法并在您的程序中实现相同的算法。此外,您可以使用 MATLAB RK 求解器的结果检查您的 C++ 结果

希望这可以帮助!祝你好运。