Ask Your Question

Revision history [back]

If you are looping over the values, you could also use an iterator:

def agen(max=Infinity):
    n = 1
    an = 1
    while n <= max:
        yield an
        n += 1
        an = (an + 1)/an^2

sage: a = agen(10)
sage: a.next()
1
sage: a.next()
2
sage: a.next()
3/4
sage: a.next()
28/9

The iterator will holds its place, and just return the next values:

sage: for i in a:
    print i.n()
....:     
0.424744897959184
7.89733878022166
0.142658807621492
56.1460737783674
0.0181279048720525
3098.18333611815

To start over, create a new instance:

sage: b = agen(20)
sage: for i in b:
    print i.n()
....:     
1.00000000000000
2.00000000000000
0.750000000000000
3.11111111111111
0.424744897959184
7.89733878022166
0.142658807621492
56.1460737783674
0.0181279048720525
3098.18333611815
0.000322873975252950
9.59564379989618e6
1.04213966781966e-7
9.20763703388443e13
1.08605497406118e-14
8.47805797477591e27
1.17951540668302e-28
7.18774670236615e55
1.39125659460260e-56
5.16637026573754e111