First page Back Continue Last page Overview Graphics

PI with Generators

The following sequence converges to π/4

π/4 = 1 - 1/3 + 1/5 - 1/7 + ...

The implemenation as a generator:

def pi_series():

sum = 0

i = 1.0

j = 1

while True:

sum = sum + j/i

yield 4*sum

i = i + 2

j = j * - 1

for i in pi_series():

print(i)

Exercise:

The program has to be stopped with Crtl-C. Add an exit condition!