c++ - 在boost中为动态数组定义自定义步进器

标签 c++ boost vector ode integrator

我如何在 boost 中为 ODE 积分器创建自定义步进器?我知道如何为编译时已知大小的数组执行此操作。一个简单的实现是这样的

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

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

typedef boost::array<double, 2> state_type;

template <size_t N>
class euler_stepper {
public:
    typedef double value_type;
    typedef double time_type;
    typedef unsigned short order_type;

    typedef boost::numeric::odeint::stepper_tag stepper_category;

    static order_type order(void) { return(1); }

    template<class System>
    void do_step(System system, state_type &x, time_type t, time_type dt) const {
        state_type der;
        system(x , der);
        for(size_t i=0 ; i<x.size(); i++) {
            x[i] += dt*der[i];
        }
    }
};

struct rhs {
    void operator()(const state_type &x, state_type &dxdt) const {
        for(int i=0; i < x.size(); i++) dxdt[i] = -x[i];
    }
};

struct observer {
    void operator()(const state_type &x , double t) const {
        for(int i=0; i < x.size(); i++) cout << x[i] << '\t';
        cout << endl;
    }
};

int main(int argc , char **argv) {  
    double dt = 0.01;
    state_type x = {{2.0, 1.0}};
    integrate_const(euler_stepper<2>(), rhs(), x, 0.0, 0.1, dt, observer());
    return 0;
}

但是如果我想使用这样的 state_type,我应该如何更改实现

typedef vector<complex<double>> state_type;

基本上,我想将状态 vector 的大小作为参数传递给 main。

谢谢,

佐尔坦

最佳答案

试试这个:

template < typename State >
class euler_stepper {
public:
    using state_type = State;
    using value_type = typename state_type::value_type;
    using time_type = value_type;
    using order_type = unsigned short;

    using stepper_category = boost::numeric::odeint::stepper_tag;

    static order_type order(void) { return(1); }

    template<class System>
    void do_step( System system , state_type &x , time_type t , time_type dt ) const
    {
        state_type der;
        system(x , der);
        for(size_t i=0 ; i<x.size(); i++) {
            x[i] += dt*der[i];
        }
    }
};

您还可以为求解器修复状态类型,例如:

class euler_stepper
{
public:
    using state_type = vector< complex< double > >;
    using value_type = double;
    using time_type = double;
    // ...
};

关于c++ - 在boost中为动态数组定义自定义步进器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33575056/

相关文章:

c++ - 不存在的行上的C++编译错误

c++ - 如何创建知道其实例在另一个类的矩阵中的方法

c++ - 在 Mac OS X 上编译 Vowpal Wabbit 时找不到头文件

c++ - 实现一个动态数组(我可以访问不存在的位置)

c++ - 在结构 vector 中初始化一个 vector

c++ - 无论如何传递函数作为模板参数?

c++ - boost spirit 还原解析

c++ - 如何使用 boost::iostreams:filtering_istream 解压缩 boost::asio::streambuf 中的数据?

Android Studio 矢量资源失真

C++ catch(std::exception & e) 与 catch(...)