使用boost:odeint的简单C ++程序中的断言错误

时间:2014-06-05 17:26:43

标签: c++ boost odeint

如果这很明显,我很抱歉,但我对来自Python / MATLAB / Mathematica背景的C ++非常陌生。我使用有限差分空间离散化为经典的1D热方程编写了一个简单的求解器,以便使用Odeint库的功能并将性能与其他库进行比较。代码应该是不言自明的:

#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/array.hpp>
#include <boost/numeric/odeint.hpp>

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

const double a_sq = 1;
const int p = 10;
const double h = 1 / p;

double pi = boost::math::constants::pi<double>();

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


void heat_equation(const state_type &x, state_type &dxdt, double t)
{
    int i;
    for (i=1; i<p; i++)
    {
        dxdt[i] = a_sq * (dxdt[i+1] - 2*dxdt[i] + dxdt[i-1]) / h / h;
    }     
    dxdt[0] = 0;
    dxdt[p] = 0;
}

void initial_conditions(state_type &x)
{
   int i;
   for (i=0; i<=p; i++)
   {
      x[i] = sin(pi*i*h);
   }
}

void write_heat_equation(const state_type &x, const double t)
{
   cout << t << '\t' << x[0] << '\t' << x[p] << '\t' << endl;
}

int main()
{
    state_type x;
    initial_conditions(x);    
    integrate(heat_equation, x, 0.0, 10.0, 0.1, write_heat_equation);
}

使用g ++ 4.8.2和Ubuntu存储库中的最新boost库,在Ubuntu 14.04上编译得很好。但是,当我运行生成的可执行文件时,出现以下错误:

***** Internal Program Error - assertion (i < N) failed in T& boost::array<T, N>::operator[](boost::array<T, N>::size_type) [with T = double; long unsigned int N = 10ul; boost::array<T, N>::reference = double&; boost::array<T, N>::size_type = long unsigned int]:
/usr/include/boost/array.hpp(123): out of range
Aborted (core dumped)

不幸的是,这对我的新手大脑并没有特别的帮助,我对如何解决这个问题感到茫然。导致错误的原因是什么?

1 个答案:

答案 0 :(得分:0)

计算数组的元素或N元素的向量从零开始。最后一个元素的索引为N-1。因此,您需要将for循环更改为从i迭代到p-1,并且需要修改行dxdt [p] = 0;到dxdt [p-1] = 0:

for (i=1; i<p-1; i++)
{
    dxdt[i] = a_sq * (dxdt[i+1] - 2*dxdt[i] + dxdt[i-1]) / h / h;
}     
dxdt[0] = 0;
dxdt[p-1] = 0;
相关问题