Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coinflips.py
- # a program to test the concept presented at
- # http://www.khanacademy.org/math/probability/v/dependent-probability-example-1
- # by Daniel Veazey <danielveazey@gmail.com>
- import random
- # what happens when you flip a coin a number of times, depending on
- # whether the coin is fair or unfair (weighted)
- # a pseudo-random number is genereated from 1 to 100
- # and compared to what its odds of landing on heads are
- # return 1 for heads if result is below odds
- # or return 0 for tails if the result is above the odds
- def flipping(how_many_flips, odds):
- no_of_heads = 0
- for flip in range(0, how_many_flips):
- flip_result = random.randint(1, 100)
- if flip_result <= odds:
- no_of_heads += 1
- if no_of_heads == how_many_flips:
- return 1
- else:
- return 0
- # choosing a coin pseudo-randomly
- # pseudo-random integer is generated from the number of coins available
- # and compared to the number of fair coins available
- # return "unfair" if it is above the number of fair coins
- # or return "fair" if it is equal to or less than number of fair coins
- def choosing_coin(how_many_fair, how_many_unfair):
- total_coins = how_many_fair + how_many_unfair
- chosen_coin = random.randint(1, total_coins)
- if chosen_coin > how_many_fair:
- return "unfair"
- else:
- return "fair"
- # ask user for parameters of test
- print "Testing probability of fair and unfair coin flips when a random coin is pulled from a bag.\n"
- fair_coins = float(raw_input("How many fair coins do you wish to put in the bag? "))
- unfair_coins = float(raw_input("How many unfair coins do you wish to put in the bag? "))
- unfair_odds = float(raw_input("For the unfair coins, what percent chance does one flip have that it will come up heads? "))
- number_of_flips = float(raw_input("How many times do you want to flip the coin chosen from the bag? "))
- # tell the user what the probability is
- print "\nThe chances of getting", int(number_of_flips), "heads in a row are about", float("%.4f" % ((((unfair_odds / 100.00) ** number_of_flips) * unfair_coins / (fair_coins + unfair_coins)) + ((.50 ** number_of_flips) * fair_coins / (fair_coins + unfair_coins))))*100.00, "percent."
- print "I am now running the simulation 100,000 times. This may take a few seconds.\n"
- # the simulation: success is the number of times the flips came up all heads
- success = 0
- for x in range(100000):
- # choose a coin
- if choosing_coin(fair_coins, unfair_coins) == "unfair":
- # flipping an unfair coin
- if flipping(int(number_of_flips), (unfair_odds)) == 1:
- success += 1
- # flipping a fair coin
- else:
- if flipping(int(number_of_flips), 50) == 1:
- success += 1
- print "Simulation complete. All heads came up", success, "out of 100,000 times."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement