A more elaborate example for a generator is its use for an iteration based on iteratively computing arithmetic and geometric means – the so-called AGM iteration, see [1]:

We demonstrate this iteration here in the context of computing elliptic integrals for determining the period of a mathematical pendulum.
When started with the values
, the AGM iteration generates a sequence of numbers with the following (astonishing) property:

The integral on the right-hand side is called a complete elliptic integral of the first kind. We'll now proceed to compute this elliptic integral. We use a generator to describe the iteration:
def arithmetic_geometric_mean(a, b):
"""
Generator for the arithmetic and geometric mean
a, b initial values
"""
while True: # infinite loop
a, b = (a+b)/2, sqrt(a*b)
yield a, b
As the sequences
converge to the same...