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


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

Re: Coin Toss Sim

From Bill Rowe <readnews@sbcglobal.net>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Coin Toss Sim
Date 2011-10-29 11:22 +0000
Organization Steven M. Christensen and Associates, Inc and MathTensor, Inc.
Message-ID <j8gnkv$5fl$1@smc.vnet.net> (permalink)

Show all headers | View raw


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.

Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web