Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #6002 > unrolled thread

Re: Coin Toss Sim

Started byBill Rowe <readnews@sbcglobal.net>
First post2011-10-29 11:22 +0000
Last post2011-10-29 11:22 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.soft-sys.math.mathematica


Contents

  Re: Coin Toss Sim Bill Rowe <readnews@sbcglobal.net> - 2011-10-29 11:22 +0000

#6002 — Re: Coin Toss Sim

FromBill Rowe <readnews@sbcglobal.net>
Date2011-10-29 11:22 +0000
SubjectRe: Coin Toss Sim
Message-ID<j8gnkv$5fl$1@smc.vnet.net>
On 10/28/11 at 5:32 AM, weh@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.

[toc] | [standalone]


Back to top | Article view | comp.soft-sys.math.mathematica


csiph-web