Computing Pi

Archimedes (250 BC) π via Polygons 0.5

Estimates π using the perimeters of regular polygons inscribed in and circumscribed about a circle of diameter 1. In the function below, each iteration doubles the number of polygon sides.

function polygon(n)
    # start with a hexagon
    a = 2 √3
    b = 3
    for i in 1:n
      a = (2 a b) / (a + b)
      b = √(a b)
    end
    return (a + b) / 2
end

polygon(4)=3.14187327526794, good to 4 significant digits for a 96-sided polygon

Viete (1597)

2π=222+222+2+22

function viete(numTerms)
   product = 1
   radicand = 0
   for i in 1:numTerms
      radicand = √(2.0 + radicand)
      product = product × (radicand / 2)
   end
   return 2 / product
end

viete(10)=3.1415914215112, good to 6 significant digits after 10 terms.

Leibnitz (1673)

π4=113+1517+=4n=0(-1)n1+2n

πapprox=4n=024(-1)n1+2n=3.18157668543503

Well, that converges slowly. Only 2 significant digits after 25 terms.

Ramanujan (1914)

1π=229,801n=0(4n)!(1,103+26,390n)(n!)43964n

format=f30

First, let’s calculate 2 to high precision: sqrtTwo=sqRt(2,1e-50)=1.414213562373095048801688724210

πapprox=9,8012sqrtTwo×n=02(4n)!(1,103+26,390n)(n!)43964n=3.141592653589793238462649065703

That’s 24 significant digits from 3 terms. Impressive.

Chudonovsky (1987)

1π=12n=0(-1)n(6n)!(13,591,409+545,140,134n)(3n)!(n!)3(640,3203)n+12

sqrtBigNum=sqRt(640,3203,1e-100)=512,384,047.996000749812554669927915299280

format=f43

πapprox=112n=02(-1)n(6n)!(13,591,409+545,140,134n)(3n)!(n!)3(640,3203)nsqrtBigNum=3.1415926535897932384626433832795028841971677

42 significant digits from the first 3 terms. Each term adds at least 14 digits.


Two of these methods needed high-precision square roots. We got them from a function for Square Roots via Newton’s Method.

function sqRt(a; ε = 1e-15)
    x = √a  # ~15 significant digits
    while true
        if |x² - a| ≤ ε return x
        x = (x + a / x) / 2
    end
end