2

これがすぐに明らかである場合は申し訳ありませんが、私は Python / MATLAB / Mathematica のバックグラウンドから来た C++ に非常に慣れていません。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);
}

これは、g++ 4.8.2 と Ubuntu リポジトリの最新のブースト ライブラリを使用して、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)

残念ながら、これは私の初心者の脳にとって特に役立つものではなく、これを修正する方法について途方に暮れています. エラーの原因は何ですか?

4

1 に答える 1

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;
于 2014-06-05T18:54:03.567 に答える