Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Plotting a line graph of frequency of flipping a coin on different number of trials

    Hi All,
    As a newbie, I have been trying to write a code on flipping a coin. More specifically, I write a simple code to simulate the outcomes of flipping a coin as 0 representing heads and 1 representing tails on an increasing number of trials as below:

    forvalues i = 10(10)100 {
    set obs `i'
    g trial`i' = int(2*runiform())

    However, what I was not able to do is to plot a line graph showing the frequency of each simulation vs the number of trials. For instance, the frequency of the tail is, say, 0.7 for 10 trials, 0.65 for 20 trials, and ...0.51 for 1000 simulations (as the number of trials increases, the frequency gets closer to .50). How can I draw a line graph showing each frequency of tails (or, heads) on the vertical axis and the number of trials on the horizontal axis?

    Many thanks in advance.

  • #2
    Probably more efficient ways, but here's some technique

    Code:
    clear all 
    
    set obs 10000
    set seed 1
    
    gen x = (runiform() > .5)
    gen p = .
    gen `c(obs_t)' t = _n
    
    forvalues x = 1/`=_N' {
         qui sum x in 1/`x'
         qui replace p = `r(mean)' in `x'
    }
    
    tw line p t, xtitle("Trials") xlab(, format(%10.0fc))

    Comment


    • #3
      This is beautiful! Many thanks.

      Comment


      • #4
        Here is another way to do it without a loop:

        Code:
        clear all
        
        set obs 10000
        set seed 314159265
        set scheme s1color
        
        gen probability = sum(runiformint(0, 1)) / _n
        gen `c(obs_t)' t = _n
        
        tw line p t, xtitle("Trials") xlab(1 10 100 1000 1000 10000, format(%10.0fc)) xsc(log) yli(0.5) yla(0.4 0.5 0.6)
        Click image for larger version

Name:	coinflip.png
Views:	1
Size:	23.3 KB
ID:	1705744

        A square root scale is another possibility.

        Comment


        • #5
          Thank you so much, Nick. This looks great.

          Comment

          Working...
          X