Wednesday, March 18, 2015

Go, pi

I have a friend who used to know \(\pi\) to about 50 places. I can barely remember nine. But on pi day last weekend, I wrote a little Go program that approximates \(\pi\) by calculating many terms of an infinite series (Nilakantha's Series).

You can express Nilakantha's series as: $$\pi = 3 + \frac{4}{2\times3\times4} - \frac{4}{4\times5\times6} + \frac{4}{6\times7\times8} - \frac{4}{8\times9\times10} + \dots$$

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.141592653589793238462643383279502884197
If 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 \(\pi\). And the Wikipedia page on \(\pi\).

No comments: