Leibniz formula for approximation of pi
pi ≈ 4 * sum[ (-1)**k / (2*k + 1) ]
for k=0 .. inf
The script shows the approximation after a first number of iterations.
Matplotlib and numpy are used to plot the values.
The code optimises the formula by
-
using a variable “denom” which starts at 1 and increases by 2 instead off calculating (2*k + 1) each iteration
-
using variable “sign” which toggles between +1 and -1, instead off calculating (-1)**k