### Computing pi

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|$ over $[-1,1]$ you get

$|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 $T_n(x) = \cos(n\arccos x)$ as usual. If you combine the fractions you get

$|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/n^2$.

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

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

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

$\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 $e^{i\pi} = -1$, and $e^x$ is easy to compute via its taylor series. meaning we can treat computing $\pi$ as finding a root of

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

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

$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))

print(x.real)
# => 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).