我得到了以下作业问题来解决:
我在用 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
}
}