Computing pi

Added 2022-03-15, Modified 2022-03-16

Two wierd methods I came up with while messing around on pi day!

I was messing around today and I found a few wierd ways to calculate π\pi

Via Chebyshev

If you compute the Chebyshev polynomial approximation for the absolute value function x|x| over [1,1][-1,1] you get

x=2π+2πn=0(1)n(12n+112n+3)T2n+2(x)|x| = \frac{2}{\pi} + \frac{2}{\pi} \sum_{n=0}^\infty (-1)^{n}\left(\frac{1}{2n+1}-\frac{1}{2n+3}\right)T_{2n+2}(x)

Where Tn(x)=cos(narccosx)T_n(x) = \cos(n\arccos x) as usual. If you combine the fractions you get

x=2π+4πn=0(1)nT2n+2(x)(2n+1)(2n+3)|x| = \frac{2}{\pi} + \frac{4}{\pi} \sum_{n=0}^\infty \frac{(-1)^{n} T_{2n+2}(x)}{(2n+1)(2n+3)}

Which converges like (1)n/n2(-1)^n/n^2.

To compute π\pi plug in x=1x = 1, since arccos(1)=0\arccos(1) = 0 and cos(0)=1\cos(0) = 1 we have T2n+2(1)=1T_{2n+2}(1) = 1 so our series becomes

1=2π+4πn=0(1)n(2n+1)(2n+3)1 = \frac{2}{\pi} + \frac{4}{\pi} \sum_{n=0}^\infty \frac{(-1)^{n}}{(2n+1)(2n+3)}

Multiply by π/2\pi/2 to get a series for π\pi.

π2=1+2n=0(1)n(2n+1)(2n+3)\frac{\pi}{2} = 1 + 2 \sum_{n=0}^\infty \frac{(-1)^{n}}{(2n+1)(2n+3)}

See it on desmos.

Via euler's formula

We know eiπ=1e^{i\pi} = -1, and exe^x is easy to compute via its taylor series. meaning we can treat computing π\pi as finding a root of

f(x)=eix+1f(x) = e^{ix} + 1

We can use newton's method, first notice f(x)=ieixf'(x) = ie^{ix} then our update equation is

xeix+1ieix=x+i(1+eix)x - \frac{e^{ix} + 1}{ie^{ix}} = x + i(1 + e^{-ix})

Geometrically this equation is extracting the height on the circle as a correction term

In [1]: from cmath import exp

In [2]: exp(-3 * 1j)
Out[2]: (-0.9899924966004454-0.1411200080598672j)

In [3]: 1 + exp(-3 * 1j)
Out[3]: (0.010007503399554585-0.1411200080598672j)

In [4]: i * (1 + exp(-3 * 1j))
Out[4]: (0.1411200080598672+0.010007503399554585j)

In code

from cmath import exp

x = 3
for i in range(5):
  x = x + 1j*(1 + exp(-1j*x))

# => 3.141592653589793

All digits correct after 5 iterations!

Of course, using exp from the standard library is cheating. But the point of this method is that computing exp(x) is a lot easier then computing π\pi directly (you can use the taylor series for instance).