News for hackers. Stuff that matters.
Re:Quick puzzle: how long to get to heaven? by gjm11 on Tuesday November 23, 2010 @07:05AM (#1933429)
The answer to any question of this form is: Unless you happen to be able to solve it quickly by doing mathematics, simulate!

  import random
  def one():
    n = 0
    while True:
      k = random.randint(0,2)
      if k==0: return n
      n += k
  def many(k):
    return sum(one() for i in range(n)) / float(n)
  [many(1000) for i in range(10)]
  many(100000)
will make it pretty easy to guess what the right answer is.

The previous-but-one posting on the same blog has a distinctly more difficult question: repeatedly pick independent random numbers uniform on [0,1]; stop when your latest number is smaller than some previous one; what's the average number of numbers you have to pick? Exercise for the reader: provide the appropriate definition of one() to make the calculation above work. It's only a few lines.

(Mathematically expert readers will be able to solve both these problems rigorously and quickly without simulating. But if such a problem comes up in a context where you actually care about the answer you'd do well to do the simulation anyway, since it's an easy way to check your reasoning.)

Re:Quick puzzle: how long to get to heaven? by ojbyrne on Tuesday November 23, 2010 @08:22AM (#1933572)
I know you just tossed off that code, but I wanted to run it. I think n should have been k in the line "return sum(one() for i in range(n)) / float(n)"
Re:Quick puzzle: how long to get to heaven? by gjm11 on Tuesday November 23, 2010 @09:58AM (#1933857)
Actually it should have been "def many(n)" instead of "def many(k)" :-), but yes. Thanks for the bugfix. Too late to edit it in, alas.