首页 > 解决方案 > 为什么 rk4.do_step 在 C++ 中不输出初始条件?

问题描述

如果我使用 rk4 步进器,我的输出值是正确的,除了我在结果中没有初始条件,就像我使用积分或积分常量选项一样,我会将初始条件作为我的输出的一部分。这与我的 for 循环有关吗?

样本:

int main(int argc, char** argv)
{
    state_type x = { 0, 895.1170, 16000, 0 }; // initial conditions
    double t = 0.0;
    double t1 = 10;
    double dt = 1;
    size_t nSteps = 1000;

    //integrate(odeFunc, x, t, t1, dt, my_observer);

    runge_kutta4<state_type>rk4;
    ofstream myfile("data.txt");
    if (myfile.is_open()){
        for (int i = 0; i < 19; ++i) {
        
            t += dt;
            rk4.do_step(odeFunc, x, t, dt);

            myfile << t << "   " << x[2] << endl;
        }
    }

}

结果:

1   16001
2   16005.4
3   16015
4   16032
5   16058.5
6   16096.5
7   16148.4
8   16216.4
.
.
.

但我想拥有

1   16000
2   16001
3   16005.4

标签: c++boost

解决方案


我使用Integrate_const 函数解决了我的问题,并且还有一个观察者函数。我使用了static ofstream 以便它保持我的文件打开并且不会在每次迭代中覆盖。

void my_observer(const state_type& x, const double t)
{
    static ofstream data("data.txt");
    data << t << "   " << x[2] << std::endl;
}

int main(int argc, char** argv)
{
    state_type x = { 0, 895.1170, 16000, 0 }; // initial conditions
    double t = 0.0;
    double t1 = 19;
    double dt = 1;


    integrate_const(runge_kutta4<state_type>(), odeFunc, x, t, t1, dt, my_observer);}

推荐阅读