xrk4.cpp

来自「这是C++数值算法(第二版)的源代码,其中包含了目前一些比较常用的数值计算的算法」· C++ 代码 · 共 46 行

CPP
46
字号
#include <iostream>
#include <iomanip>
#include "nr.h"
using namespace std;

// Driver for routine rk4

void derivs(const DP x, Vec_I_DP &y, Vec_O_DP &dydx)
{
        dydx[0]= -y[1];
        dydx[1]=y[0]-(1.0/x)*y[1];
        dydx[2]=y[1]-(2.0/x)*y[2];
        dydx[3]=y[2]-(3.0/x)*y[3];
}

int main(void)
{
        const int N=4;
        int i,j;
        DP h,x=1.0;
        Vec_DP y(N),dydx(N),yout(N);

        y[0]=NR::bessj0(x);
        y[1]=NR::bessj1(x);
        y[2]=NR::bessj(2,x);
        y[3]=NR::bessj(3,x);
        derivs(x,y,dydx);
        cout << endl << setw(16) << "Bessel function:";
        cout << setw(6) << "j0" << setw(13) << "j1";
        cout << setw(13) << "j3" << setw(13) << "j4" << endl;
        cout << fixed;
        for (i=0;i<5;i++) {
          h=0.2*(i+1);
          NR::rk4(y,dydx,x,h,yout,derivs);
          cout << setprecision(2);
          cout << endl << "for a step size of: " << setw(6) << h << endl;
          cout << setprecision(6);
          cout << setw(12) << "rk4:";
          for (j=0;j<4;j++) cout << setw(13) << yout[j];
          cout << endl << setw(12) << "actual:" << setw(13) << NR::bessj0(x+h);
          cout << setw(13) << NR::bessj1(x+h) << setw(13) << NR::bessj(2,x+h);
          cout << setw(13) << NR::bessj(3,x+h) << endl;
        }
        return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?