You can express Nilakantha's series as: π=3+42×3×4−44×5×6+46×7×8−48×9×10+…
Here's the Go program:
package main import ( "fmt" "os" "strconv" ) const ndefault = 10000 func main() { // How many iterations? n := ndefault if (len(os.Args) > 1) { n,_ = strconv.Atoi(os.Args[1]) } if n == 0 { n = ndefault } fmt.Println("n =", n) pi := 3.0 s := 1.0 // Sign for alternating terms // Nilakantha series. for i := 2.0; i <= float64(n*2); i += 2 { pi = pi + s * (4 / (i * (i + 1) * (i + 2))); s = -s } fmt.Printf("%1.20f\n", pi) }
Not perfect, but not bad (maybe I'm doing something wrong):
Starts going off rails here. | approx: 3.14159265358953820879 actual: 3.141592653589793238462643383279502884197If you really want to know more about the history and the mathematics, there's a nice paper here from the Mathematical Association of America: The Discovery of the Series Formula for π. And the Wikipedia page on π.
No comments:
Post a Comment