I'm herewith archiving an email from earlier today, to the guy in charge of
the Python curriculum at this company I work for (see LinkedIn profile). It
refers back to this listserv, in the context of recycling what I consider a
choice piece of Python lore: that generator for deriving digits of pi.  --
Kirby



---------- Forwarded message ---------
From: Kirby Urner <ki...@clarusway.com>
Date: Wed, Jul 24, 2024 at 4:05 PM
Subject: Python generators (a fun example, not by me)
To:




On the topic of Python generators, I just wanted to share what I consider a
mysterious one, meaning I didn't write it and don't understand why it works
(eyeballing the code has not yielded answers).

It may have actually come to me from Guido himself if I remember how it
went on edu-sig (one of the archived Python.org discussion groups on which
I've been active). He and I have a long term shared interest around
integrating Python into everyday math learning (we've come a long way since
then).

For context, I'm copying this Python generator from my Jupyter Notebook
called Pi Day, which is about using Python to generate the number pi in
various ways:

https://nbviewer.org/github/4dsolutions/Python5/blob/master/Pi%20Day%20Fun.ipynb

Although most of the Python is by me, I'm simply implementing algorithms
discovered by others (it's about their genius, not mine), such as that
famous one by Ramanujan in the middle of the page.

Here's the generator I'm talking about (at the very end of the above
notebook, before the flashing GIF pizza pi):

"""
Another generator example:  converging to Pi

https://mail.python.org/pipermail/edu-sig/2015-September/date.html

"""

def pi():

    k, a, b, a1, b1 = 2, 4, 1, 12, 4
    while True:
        p, q, k = k*k, 2*k+1, k+1
        a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
        d, d1 = a/b, a1/b1
        while d == d1:
            yield int(d)
            a, a1 = 10*(a%b), 10*(a1%b1)
            d, d1 = a/b, a1/b1

if __name__ == "__main__":
    the_gen = pi()
    for _ in range(100):
        print(next(the_gen),end="")
    print()

If I run that I get (I also have 3.9 as well as 3.11):

Python 3.9.12 (main, Apr  5 2022, 01:53:17)
Type "copyright", "credits" or "license" for more information.

IPython 7.31.1 -- An enhanced Interactive Python.

runfile('/Users/kirbyurner/Documents/clarusway_data_analysis/python_warm_up/pi_generator.py',
wdir='/Users/kirbyurner/Documents/clarusway_data_analysis/python_warm_up')
3141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067

Those are the digits of pi <https://www.piday.org/million/>!  Why?  Pretty
interesting, no?

Kirby
_______________________________________________
Edu-sig mailing list -- edu-sig@python.org
To unsubscribe send an email to edu-sig-le...@python.org
https://mail.python.org/mailman3/lists/edu-sig.python.org/
Member address: arch...@mail-archive.com

Reply via email to