Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2011

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

Search the Archive

Re: Coin Toss Sim

  • To: mathgroup at smc.vnet.net
  • Subject: [mg122469] Re: Coin Toss Sim
  • From: Bill Rowe <readnews at sbcglobal.net>
  • Date: Sat, 29 Oct 2011 07:12:17 -0400 (EDT)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com

On 10/28/11 at 5:32 AM, weh at snafu.de (Dr. Wolfgang Hintze) wrote:


>If I avoid RandomChoice it works fine:

>y[n_] := Block[{g, s},
>g := Table[If[Random[] < 1/2, "head", "tail"], {n}];
>s := Count[g, "head"]; {g, s}]
>y[10]

>{{"tail", "head", "head", "head", "tail", "tail", "tail", "head",
>"head", "tail"}, 3}

Actually, replacing RandomChoice with If[...] as you've done
makes no difference. The code still fails at times. But a single
test isn't sufficient to show that it fails. To demonstrate:

In[1]:= y[n_] := Block[{g, s},
   g := Table[If[Random[] < 1/2, "head", "tail"], {n}];
   s := Count[g, "head"]; {g, s}]

In[2]:= Count[
  Table[x = y[10]; Count[x[[1]], "head"] == x[[2]], {100}], True]

Out[2]= 17

The problem is (as others have pointed out and I missed in my
initial response) is g is evaluated twice, once when called by
Count and then again when returned as part of the output. And
since it is defined with SetDelayed, there should be no
expectation the results of both calls have the same number of
heads. To work as intended, g needs to be defined with Set
rather than SetDelayed. With this change:

In[3]:= Clear[y];
y[n_] := Block[{g, s},
   g = Table[If[Random[] < 1/2, "head", "tail"], {n}];
   s := Count[g, "head"]; {g, s}]

In[5]:= Count[
  Table[x = y[10]; Count[x[[1]], "head"] == x[[2]], {100}], True]

Out[5]= 100

Everyone of the 100 calls to y a list of coin tosses paired with
a count of the heads in that list.




  • Prev by Date: Re: Clean up code to run faster
  • Next by Date: PopupMenu Problems
  • Previous by thread: Re: Coin Toss Sim
  • Next by thread: Conditional Import