Welcome, guest | Sign In | My Account | Store | Cart

This program is equivalent to tossing a coing for 100 times and for 100 attempts to obtain the number of heads and tails in the random order it also sums up the number of heads and tails that have formed so far....this is a simple program for random sample space analysis to show that even in the best of conditions the probability of a coin falling tails or heads is not exactly 1/2..but close to 1/2. The UINIVERSE is not perfect !

Python, 14 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import random
h,t,sumh,sumt=0,0,0,0
for j in range(1,101):
    for i in range(1,101):
        x=random.randint(1,2)
        if (x==1):
            h=h+1
        else:
            t=t+1
    print "Heads are:", h, "Tails are", t
    sumh=sumh+h
    sumt=sumt+t
    h,t=0,0
print "Heads are:", sumh, "Tails are", sumt

1 comment

Sean Ross 18 years, 7 months ago  # | flag

import random, operator

tosses = [random.choice((0,1)) for toss in xrange(100)]

nheads = reduce(operator.add, tosses) # or sum(tosses) in Python 2.3

ntails = 100 - nheads

print "heads: %s tails: %s" % (nheads, ntails)

Created by Souman Deb on Thu, 23 Jan 2003 (PSF)
Python recipes (4591)
Souman Deb's recipes (1)

Required Modules

Other Information and Tasks