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

Assertion error in a simple C++ program using boost:odeint

本文关键字:程序 断言 错误 c++ 简单 boost odeint 使用      更新时间:2023-10-16

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

#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);
}

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

***** 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)

不幸的是,这对我的新手大脑没有特别的帮助,我不知道如何解决这个问题。是什么导致了错误?

从0开始计算数组或n个元素的向量的元素。最后一个元素的索引是N-1。所以,你需要把for循环改成从i到p-1你需要修改dxdt[p] = 0这行;To 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;