MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Coin Toss Simulation

  • To: mathgroup at
  • Subject: [mg122374] Re: Coin Toss Simulation
  • From: "Tony Harker" <a.harker at>
  • Date: Thu, 27 Oct 2011 06:27:51 -0400 (EDT)
  • Delivered-to:

The problem is that you use Set Delayed (:=) everywhere rather than Set (=).
This means that neither s nor g are evaluated until they are used. So, when
{g,s} is calculated this is what happens:
  1. a value is calculated for g, and becomes the first element of the list
  2. with that done and dusted, Mathematica moves on to compute s.
    i) s requires a value for g, so
   ii) compute a new value for g (because of the SetDelayed)
  iii) count the heads
 iv) make that the second element of the list.

  As a result, the list of heads and tails and the count of heads in the
returned answer do not correspond.

 This would work:
y[n_] := Block[{g, s}, g = RandomChoice[{"head", "tail"}, n];
  s := Count[g, "head"];
  {g, s}]

Or, neater perhaps,
 y[n_]:={#,Count[#,"head"]}&[ RandomChoice[{"head", "tail"}, n]]

]-> -----Original Message-----
]-> From: pooleman133 [mailto:poolebc221 at]
]-> Sent: 26 October 2011 22:39
]-> To: mathgroup at
]-> Subject: Coin Toss Sim
]-> I am new to mathematica and am trying to make a coin flipping simulation
]-> however mo code isn't working. When I tell it to count the number of
]-> it gives me a bad count. The code I am using is listed below any help
]-> be greatly appreciated.
]-> y[n_] := Block[{g, s},
]->   g := RandomChoice[{"head", "tail"}, n];
]->   s := Count[g, "head"];
]->   {g, s}
]->   ]

  • Prev by Date: Re: Coin Toss Sim
  • Next by Date: Re: Coin Toss Sim
  • Previous by thread: struggling in integration
  • Next by thread: Re: Full simplify problem - thanks