Sugar Pie

2008-03-06, , , Comments

Question: in the code snippet bleow, what does the result stream, rs, approximate?

from itertools import count, ifilter, izip
from random import random as xy
from math import hypot

pt = lambda: (xy(), xy())
on = ifilter(lambda n: hypot(*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!

Here’s a picture of a round pie on a square baking tray being dusted with sugar.

Dusting a pie

Thanks again to Marius Gedminas for pointing me at math.hypot, the best way to find the length of a 2D vector. (The previous version of this note used abs(complex(*pt()), which it claimed to be better than math.sqrt(x * x + y * y)).