Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168740
Image: ubuntu2004
# Here is a quick way to experiment with the "first ace" random variable. # In contrast to the student version, which shows a very clever home-made shuffling algorithm, # I was lazy and just searched for an already-done function in Python. It turns out that the "random" package contains # a command which randomly shuffles a list. ############################################################## import random #import the package that contains the shuffle method. deck=range(13)*4 #define a deck of cards to be the list [0,1,2,...,12] repeated 4 times. # We will define aces to be the 4 zeros. # Now we define the first_ace() random variable. def first_ace(): random.shuffle(deck) # this shuffles deck 'in place;' i.e., the new value of deck is the scrambled one. return 1+deck.index(0) # the index method outputs the first index in the list that has the value 0. # We add 1 to it, because lists start with index 0; but decks of cards start with card #1, etc.
# Output an unshuffled deck, fresh out of the box. deck
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# Test output of the random variable. first_ace()
13
# Test that deck is now scrambled. deck
[7, 10, 1, 11, 8, 11, 10, 12, 11, 12, 5, 6, 0, 7, 3, 2, 8, 7, 10, 8, 0, 9, 4, 12, 12, 10, 3, 6, 3, 3, 4, 9, 1, 2, 6, 4, 5, 11, 5, 0, 1, 7, 5, 9, 2, 0, 4, 1, 6, 8, 2, 9]
# Now do a heavy-duty test (100,000 trials). # Create a list of 100000 outputs of the RV. outputs = [first_ace() for _ in range(100000)] # Compute the average by adding these numbers, and dividing by 100000. # Note the decimal point; that way the variable 'avg' is automatically a float # rather than an fraction. avg =sum(outputs)/100000. print(avg) # Note that it is close to 10.6.
10.6043600000000
# Finally, we display a the frequencies of the various outputs and plot them. # For example, how many times did the RV output the value 2? This is easily # found using the count() method. outputs.count(2)
7295
# Now we will make a list of all the output frequencies and plot them. # Note that the RV theoretically outputs values in the range 1, 2,..., 49, inclusive, # (And remember that the Python object range(1,50) is precisely the range 1,2,...,49, inclusive.) freq = [outputs.count(i) for i in range(1,50)] # This next command plots the values in the list. # It is clear that empirically, the most frequent outcome is 0, and it is indeed about 1/13 of the 100000 trials. list_plot(freq)
# If you are very observant, you will notice that x-axis values of the plot started with 0, # which is because Python lists start with index 0. We can remedy this in a number of ways, but I will leave them to you!