D言語で 積分(台形則)して π を求める
積分(台形則)
import std.stdio; import std.math; void main(string[] args) { const double a = 0; const double b = 1; // 台形則で積分 int n = 2; for (int j = 1; j <= 10; j++) { double h = (b - a) / n; double s = 0; double x = a; for (int i = 1; i <= n - 1; i++) { x += h; s += f(x); } s = h * ((f(a) + f(b)) / 2 + s); n *= 2; // 結果を π と比較 writefln("%2d : %13.10f, %13.10f", j, s, s - PI); } } double f(double x) { return 4 / (1 + x * x); }
Z:\>dmd D0601.d Z:\>D0601 1 : 3.1000000000, -0.0415926536 2 : 3.1311764706, -0.0104161830 3 : 3.1389884945, -0.0026041591 4 : 3.1409416120, -0.0006510415 5 : 3.1414298932, -0.0001627604 6 : 3.1415519635, -0.0000406901 7 : 3.1415824811, -0.0000101725 8 : 3.1415901105, -0.0000025431 9 : 3.1415920178, -0.0000006358 10 : 3.1415924946, -0.0000001589
参考文献