C..5 簡単な計算の例 -- 有限級数の和

単純な計算は単に型を INTERVAL にすれば良い。例えば

$\displaystyle s=\sum_{i=1}^n \frac{1}{i},\quad n=10^6
$

を精度保証付きで計算するには、
test4.cpp

// test4.cpp
// g++ -I/usr/local/include/profil -o test4 test4.cpp -lProfil -lBias -llr

#include <iostream>
#include <iomanip>
#include <Interval.h>
using namespace std;

int main(void)
{
  int i, n;
  INTERVAL s;

  cout << setprecision(18);
  n = (int)1e6;
  s = 0;
  for (i = 1; i <= n; i++)
    s += 1 / Hull(i);
  cout << "1/1+1/2+…+1/" << n << "=" << s << endl;
  cout << "幅=" << Diam(s) << endl;
 
  s = 0;
  for (i = n; i >= 1; i--)
    s += 1 / Hull(i);
  cout << "1/1+1/2+…+1/" << n << "=" << s << endl;
  cout << "幅=" << Diam(s) << endl;
 
 return 0;
}
test4 の結果

[katsurada-no-MacBook-Air-4:~/work/tmp] mk% ./test4
1/1+1/2+…+1/1000000=14.39272672[19812922,37561250]
幅=1.77483272523204505e-09
1/1+1/2+…+1/1000000=14.392726722[7861861,9463354]
幅=1.60149227212968981e-10
[katsurada-no-MacBook-Air-4:~/work/tmp] mk%

結果の相対精度は $ 1.77\times 10^{-9}/14.4\kinji 1.2\times 10^{-10}$. $ 10^6$ 回の演算をしたためか、精度が約 $ 10^6$ 倍悪くなっている。

この手の計算では、情報落ち (積み残し) を防ぐために 逆から足せと言われるが、それをすると、約 1 桁改善されている。

桂田 祐史
2020-09-03