This post originated from an RSS feed registered with Python Buzz
by Thomas Guest.
Original Post: Sugar Pie
Feed Title: Word Aligned: Category Python
Feed URL: http://feeds.feedburner.com/WordAlignedCategoryPython
Feed Description: Dynamic languages in general. Python in particular. The adventures of a space sensitive programmer.
Question: in the code snippet bleow, what does the result stream, rs, approximate?
from itertools import count, ifilter, islice, izip
from random import random as xy
pt = lambda: (xy(), xy())
on = ifilter(lambda n: abs(complex(*pt())) < 1., count(1))
rs = (4. * j / i for i, j in izip(on, count(1)))
The code isn’t wilfully obscure but I’ll admit it’s unusual. Although written in a functional style, the source of the stream, pt, is utterly impure, generating a sequence of random results: it sprinkles points in a unit square. Despite this random input the results stream always tends to the same value. Well, in theory it should!
Incidentally, applying abs() to a complex number returns the modulus of that number: it’s easier than math.sqrt(x * x + y * y). And I’m counting from 1, not 0, to avoid dividing by zero.