[Tutor] Optimizing a simple radioactive decay simulation

Bob Gailer ramrom@earthling.net
Thu Dec 12 23:30:01 2002


import random, time
start = time.time()
numcoins = int(raw_input("How many coins? "))
halflives = 0
while numcoins >= 1:
   for i in range(numcoins):
     numcoins -= random.randint(0,1)
   print "Undecayed (heads): %s" % numcoins
   halflives += 1
print "\n%s half-lives required." % halflives
print '%d seconds' % (time.time() - start)

for 1000000 coins on an almost identical machine:
Undecayed (heads): 500026
Undecayed (heads): 250149
Undecayed (heads): 125008
Undecayed (heads): 62168
Undecayed (heads): 31002
Undecayed (heads): 15513
Undecayed (heads): 7678
Undecayed (heads): 3883
Undecayed (heads): 1918
Undecayed (heads): 944
Undecayed (heads): 484
Undecayed (heads): 245
Undecayed (heads): 120
Undecayed (heads): 64
Undecayed (heads): 38
Undecayed (heads): 18
Undecayed (heads): 9
Undecayed (heads): 6
Undecayed (heads): 4
Undecayed (heads): 4
Undecayed (heads): 1
Undecayed (heads): 1
Undecayed (heads): 0
23 half-lives required.
35 seconds

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625