Go言語で 積分(台形則)して π を求める
積分(台形則)
package main import "fmt" import "math" func main() { const a = 0 const b = 1 // 台形則で積分 var n int = 2 for j := 1; j <= 10; j++ { var h float64 = (b - a) / float64(n) var s float64 = 0 var x float64 = a for i := 1; i <= n - 1; i++ { x += h s += f(x) } s = h * ((f(a) + f(b)) / 2 + s) n *= 2 // 結果を π と比較 fmt.Printf("%2d : %13.10f, %13.10f\n", j, s, s - math.Pi) } } func f(x float64) float64 { return (4 / (1 + x * x)) }
Z:\>8g GO0601.go Z:\>8l -o GO0601.exe GO0601.8 Z:\>GO0601 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
参考文献