## 5/12/2004

### A coin tossing simulator

I was thinking about the coin flipping topic again. I decided to code up a quick little python program to simulate X number of coin tosses. I ran it for several numbers of X (I think the largest was 100000) and it seems to be that most of the time it came out close to 50-50.

Now a quick disclaimer: I have no idea how random the randrange function is, so this program should be taken with a gain of salt.

How it works: You give it a number which is the number of coin tosses you want it to do. Say 100 for example. Then it takes this number and proceeds to call random.randrange() with a minimum number of 1 and a max of 100 million. (note this is an odd number and an even number). It then takes the result (somewhere inclusive to that range) and does a modulus 2 operation on it to see if it is even. If it is, it increments the heads counter if it isn't the tails counter gets incremented.

At the end of the tosses it then reports back the numbers for heads and tails. Its a decent simulation I think, and somewhat representative of what you would see if you did this in real life. A more accurate simulation would probably take into account which side of the coin was facing up when it was first flipped (see my previous posting for details on that), and it would also probably make sure the random number generator was properly seeded before every toss.... But like I said, this is a quick little demo program. Feel free to modify it.

coinflip.py (Please note you need to save it with a .py extension, I had to put the .txt on there to get it to load onto geocities.)

Now a quick disclaimer: I have no idea how random the randrange function is, so this program should be taken with a gain of salt.

How it works: You give it a number which is the number of coin tosses you want it to do. Say 100 for example. Then it takes this number and proceeds to call random.randrange() with a minimum number of 1 and a max of 100 million. (note this is an odd number and an even number). It then takes the result (somewhere inclusive to that range) and does a modulus 2 operation on it to see if it is even. If it is, it increments the heads counter if it isn't the tails counter gets incremented.

At the end of the tosses it then reports back the numbers for heads and tails. Its a decent simulation I think, and somewhat representative of what you would see if you did this in real life. A more accurate simulation would probably take into account which side of the coin was facing up when it was first flipped (see my previous posting for details on that), and it would also probably make sure the random number generator was properly seeded before every toss.... But like I said, this is a quick little demo program. Feel free to modify it.

coinflip.py (Please note you need to save it with a .py extension, I had to put the .txt on there to get it to load onto geocities.)

Comment on this post [ so far] ... more like this: [python]