IntTrap.cpp

IntTrap_functional.cpp

MultiIntTrap.cpp

LambdaIntTrap.cpp

ParaIntTrap.cpp

IntTrap.hpp

IntTrapSample.cpp


台数公式 https://ja.wikipedia.org/wiki/台形公式 は最も基本的な 1 次の数値積分法の 1 つである

Untitled

$$ \int_a^bf(x)\mathrm{d}x\simeq\sum_{i=0}^{n-1}\frac{f(x_i)+f(x_{i+1})}{2}\Delta x_i $$

特に等間隔 $\Delta x_i=\Delta x=(b-a)/n$ の場合は

$$ \int_a^bf(x)\mathrm{d}x\simeq\frac{f(a)+f(b)}{2}\Delta x+\sum_{i=1}^{n-1}f(x_i)\Delta x $$

要するに最初と最後だけ 1/2 して $f(x_i)\Delta x$ を足しあげればよい

#define _USE_MATH_DEFINES
#include <cmath> // 基本的な数学関数や定数のライブラリ。この2つはセット

#include <sys/time.h> // ストップウォッチ用
#include <iostream>

using namespace std;

// 2つの被積分関数
double ff(double x) {
  return 4./(1+x*x);
}

double gg(double x) {
  return 2*sin(2*M_PI*x)*sin(2*M_PI*x);
}

int main()
{
  // ---------------- start stop watch -----------------
  struct timeval tv;
  struct timezone tz;
  double before, after;

  gettimeofday(&tv, &tz);
  before = (double)tv.tv_sec + (double)tv.tv_usec * 1.e-6;
  // ---------------------------------------------------

  double xmin = 0; // 積分下端
  double xmax = 1; // 上端
  int istep = 1000; // 分割数 n

  double dx = (xmax-xmin)/istep;
  double IntTrap = (ff(xmin)+ff(xmax))/2.*dx; // 最初と最後だけ足しておく
  double x; // 積分変数

  for (int i=1; i<istep; i++) {
    x = xmin + i*dx;
    IntTrap += ff(x)*dx;
  }

	cout << IntTrap << endl;

  IntTrap = (gg(xmin)+gg(xmax))/2.*dx;

  for (int i=1; i<istep; i++) {
    x =	xmin + i*dx;
    IntTrap += gg(x)*dx;
  }

  cout << IntTrap << endl;

  // ---------------- return elapsed time --------------
  gettimeofday(&tv, &tz);
  after = (double)tv.tv_sec + (double)tv.tv_usec * 1.e-6;
  cout << after - before << " sec." << endl;
  // ---------------------------------------------------
}
3.14159
1
0.000714064 sec.

functional

いろいろな関数を定積分する機能をまとめておきたい。ところで定積分とは「関数形を入力すると数値を返す」手続きであるため汎関数であると言える。もちろん C 言語では数値しか引数に取れないので汎関数は定義できない。しかし C++ では「関数形そのものを変数」とする function クラスが用意されている

function<typeA(typeB)> func