[Edu-sig] another Python generator (logarithmic numbers)

kirby urner kirby.urner at gmail.com
Mon Apr 15 05:05:24 CEST 2013


from fractions import Fraction as R

def Gregory():
    """
    Gregory Coefficients (
http://en.wikipedia.org/wiki/Euler-Mascheroni_constant)
    1/2, 1/12, 1/24, 19/720, 3/160, 863/60480...
    using fraction module to keep it rational.
    """
    G = [R(-1,1)]

    def Sum(n):
        total = R(0,1)
        for k in range(0,n):
            total +=  R(G[k],n+1-k)
        return -total

    n = 1
    while True:
        G.append(Sum(n))
        yield G[-1]
        n += 1

====

>>> from anyproject import Gregory
>>> thegen = Gregory()
>>> next(thegen)
Fraction(1, 2)
>>> next(thegen)
Fraction(1, 12)
>>> next(thegen)
Fraction(1, 24)
>>> next(thegen)
Fraction(19, 720)
>>> next(thegen)
Fraction(3, 160)
>>> next(thegen)
Fraction(863, 60480)
>>> next(thegen)
Fraction(275, 24192)
>>> next(thegen)
Fraction(33953, 3628800)
>>> next(thegen)
Fraction(8183, 1036800)
...

Kirby
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20130414/a0daf998/attachment.html>


More information about the Edu-sig mailing list