Skip to content

Instantly share code, notes, and snippets.

@CountChu
Last active November 18, 2017 08:35
Show Gist options
  • Save CountChu/a70fab1c3e79cebfe7f32e554025df31 to your computer and use it in GitHub Desktop.
Save CountChu/a70fab1c3e79cebfe7f32e554025df31 to your computer and use it in GitHub Desktop.
#
# Use random numbers to emulates the Sampling with Replacement.
#
# We can specify the number of balls in the bin with 40% red balls and 60% green balls.
# We select 10 balls from the bin and calculate the probability of the red
# balls in the samples.
#
import random
def sampleingWithReplacement (total, replaceTimes):
balls = []
red = int (total * 40 / 100)
green = total - red
for i in range (red):
balls.append (1)
for i in range (green):
balls.append (0)
#print ("Display balls in the bin.")
#print (balls)
numberOfRed = 0
for i in range (replaceTimes):
random.shuffle (balls)
sample = balls [0: 10]
s = sum (sample)
if s == 0 or s == 1:
numberOfRed += 1
p = numberOfRed / replaceTimes
print ("There are %d balls in the bin. (%d red balls, %d green balls)" % (total, red, green))
print ("Select %d balls from the bin with replacement.")
print ("Times of replacement = %d" % replaceTimes)
print ("Number of red balls in the sample = %d" % numberOfRed)
print ("Probability = %f" % p)
print ("")
if __name__ == '__main__':
replaceTimes = 10000
sampleingWithReplacement (100, replaceTimes) # total = 100, probability = 0.034800
sampleingWithReplacement (1000, replaceTimes) # total = 1000, probability = 0.046900
sampleingWithReplacement (10000, replaceTimes) # total = 10000, probability = 0.047300
sampleingWithReplacement (100000, replaceTimes) # total = 100000, probability = 0.043800
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment