[prev in list] [next in list] [prev in thread] [next in thread] 

List:       python-edu-sig
Subject:    [Edu-sig] another Python generator (logarithmic numbers)
From:       kirby urner <kirby.urner () gmail ! com>
Date:       2013-04-15 3:05:24
Message-ID: CAPJgG3SE5SMY65mrRO8pfAr4BO2U5nWYU=-bNveWK+XB2Tcjww () mail ! gmail ! com
[Download RAW message or body]

[Attachment #2 (multipart/alternative)]


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

[Attachment #5 (text/html)]

<div dir="ltr"><div>from fractions import Fraction as R<br><br>def Gregory():<br>    \
&quot;&quot;&quot;<br>    Gregory Coefficients (<a \
href="http://en.wikipedia.org/wiki/Euler-Mascheroni_constant">http://en.wikipedia.org/wiki/Euler-Mascheroni_constant</a>)<br>
  1/2, 1/12, 1/24, 19/720, 3/160, 863/60480...<br>    using fraction module to keep \
it rational.<br>    &quot;&quot;&quot;<br>    G = [R(-1,1)]<br><br>    def \
Sum(n):<br>        total = R(0,1)<br>        for k in range(0,n):<br>  total +=  \
R(G[k],n+1-k)<br>        return -total<br><br>    n = 1<br>    while True:<br>        \
G.append(Sum(n))<br>        yield G[-1]<br>        n += \
1<br><br>====<br><br>&gt;&gt;&gt; from anyproject import Gregory<br> &gt;&gt;&gt; \
thegen = Gregory()<br>&gt;&gt;&gt; next(thegen)<br>Fraction(1, 2)<br>&gt;&gt;&gt; \
next(thegen)<br>Fraction(1, 12)<br>&gt;&gt;&gt; next(thegen)<br>Fraction(1, \
24)<br>&gt;&gt;&gt; next(thegen)<br>Fraction(19, 720)<br> &gt;&gt;&gt; \
next(thegen)<br>Fraction(3, 160)<br>&gt;&gt;&gt; next(thegen)<br>Fraction(863, \
60480)<br>&gt;&gt;&gt; next(thegen)<br>Fraction(275, 24192)<br>&gt;&gt;&gt; \
next(thegen)<br>Fraction(33953, 3628800)<br>&gt;&gt;&gt; next(thegen)<br> \
Fraction(8183, 1036800)<br>...<br><br></div>Kirby<br><br></div>



_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic