[Tutor] optimizing a simple radioactive decay simulation
Joshua Pollack
j.pollack@m.cc.utah.edu
Fri Dec 20 14:46:17 2002
This is a multi-part message in MIME format.
--Boundary_(ID_nfgE2KDQiWnFJZ5cFG1KgA)
Content-type: text/plain; charset=us-ascii; format=flowed
Content-transfer-encoding: 7BIT
Hi guys:
I just finished the semester and had some time to look back at the
archives. My programming skills
are only so-so, I'm pretty new to python, but I have had a little
probability theory and this shortcut makes the radioactive decay
simulation short and sweet. Instead of flipping coins more than a
million times, you can draw a binomial random variable with a mean equal
to the remaining coins and prob of success 0.5. It's kind of cheating
in that you don't actually flip all those coins but works just as well
and is quite a bit faster. Here's my output for one such simulation.
Undecayed heads: 499479
Undecayed heads: 249731
Undecayed heads: 125012
Undecayed heads: 62644
Undecayed heads: 31278
Undecayed heads: 15499
Undecayed heads: 7616
Undecayed heads: 3778
Undecayed heads: 1867
Undecayed heads: 916
Undecayed heads: 493
Undecayed heads: 239
Undecayed heads: 128
Undecayed heads: 64
Undecayed heads: 34
Undecayed heads: 21
Undecayed heads: 10
Undecayed heads: 5
Undecayed heads: 4
Undecayed heads: 3
Undecayed heads: 3
Undecayed heads: 2
Undecayed heads: 2
Undecayed heads: 0
Halflives: 24
0.235000014305 seconds
P.S.- thanks to Bob Gailer for providing the structure, I just changed
the flipping mechanism.
Joshua Pollack
UC Berkeley
Integrative Biology
jpollack@socrates.berkeley.edu
--Boundary_(ID_nfgE2KDQiWnFJZ5cFG1KgA)
Content-type: text/plain; name=flipper.py
Content-transfer-encoding: 7BIT
Content-disposition: inline; filename=flipper.py
import time,rv
start=time.time()
numcoins=1000000
halflives=0
while numcoins>=1:
newgeneration=rv.binomial(numcoins,0.5)
halflives+=1
print "Undecayed heads:",newgeneration
numcoins=newgeneration
print "Halflives:", halflives
print time.time()-start,"seconds"
--Boundary_(ID_nfgE2KDQiWnFJZ5cFG1KgA)--