Python for simple random simulations-toss and toss coins

Source: Internet
Author: User

Or in the last mention of the charm of the book, see the simulation of this chapter, there is a Python simulation script, but the book is not complete, they simply wrote down.

Process: Under different equilibrium parameters P (uniform at 0.5), simulate 60 experiments, each coin 8 times, count the number of positive face up, and plotted.

Import Randomimport Matplotlib.pyplot as pltrepeats, tosses =, 8# p is the balance parameter, tosses is the number of coins thrown in each repetition test # Returns the current equilibrium parameter p,     Number of positive times in 8 experiments def heads (tosses, p): h = 0 for x in range (0, tosses): if Random.random () < P:h + = 1 return HX = [] # store balance parameter py = [] # Store each p, 60 repetitions of the H value p = 0 # Initialize p, starting from 0 while p < 1.01:hh = [] for T in RA        Nge (0, repeats): H = Heads (tosses,p) # Add a small jitter value to prevent overlapping of points H + = (Random.random ()/4) *random.choice ([ -1,1]) Hh.append (h) #print (p, ' t ', Heads (tosses,p)) y.append (HH) x.append (p) p + = 0.05# arrows Callout p=0.5, that is, the point pl of the coin balance T.plot (x, y, ' g^ ') plt.annotate (' Balence ', xy= (0.5, 5), xytext= (0.15, 8), arrowprops=dict (facecolor= ' black ', Shrin k=0.05),) plt.show () "# An interesting attempt ... # start not to make the ideal picture, think an x, corresponding to multiple Y can not draw (in fact, forget the point of jitter) ... # Here the Loop plot is also possible. For I in range (6 0): Q = [] for n in range (len (y)): yn = y[n][i] q.append (yn) plt.plot (x,q, ' ro ') '

The output graph is as follows:

It can be seen that, in the case of p=0.5, where the coin is evenly spaced, the number of positive occurrences of the coin is mostly near 4.

Python for simple random simulations-toss and toss coins

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.