Search code examples
c++odeint

odeint resets the object while iteration


Running the following code:

#include <iostream>
#include <boost/numeric/odeint.hpp>

using namespace std;
using namespace boost::numeric::odeint;

class CSystem
{
private:
    int counter=0;
public:

    void operator() ( const double &x , double &dxdt , const double t)
    {
        double mat_A=-1;
        double mat_B=1;

        dxdt=mat_A*x+mat_B*1;

        cout<<"counter: "<<counter<<endl;
        counter++; // seems it does not apply to the rest of the iterations appropriately
    }

    void solve()
    {
        double x;
        x = 0.0;
        typedef runge_kutta_dopri5<double> stepper_type;
        std::function<void(const double &,const double)> my_observer = [&](const double &x,const double t){/* do nothing*/};
        integrate_adaptive(make_controlled(1E-10,1E-10,stepper_type()),
                            *this,x,0.0,3.0,0.1,my_observer);
    }

};

int main()
{
    CSystem sys;
    sys.solve();
    return 0;
}

I expect that the counter starts counting from 0 up and cout generates the following output:

0
1
2
3
4
5
6
7
8
9
10
11
...

While I get something else:

counter: 0
counter: 0
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 0
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 0
counter: 1
counter: 2
counter: 3
...

What does reset the counter? seems odeint!

What is the correct way of fixing that? I would prefer avoid using external object.


Solution

  • Your use of *this makes a copy of your CSystem object, which possibly gets copied further.

    I think you should change that parameter to std::ref(*this).