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


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

Re: Coin Toss Simulation

From "Tony Harker" <a.harker@ucl.ac.uk>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Coin Toss Simulation
Date 2011-10-27 10:28 +0000
Organization Steven M. Christensen and Associates, Inc and MathTensor, Inc.
Message-ID <j8bbp0$8gn$1@smc.vnet.net> (permalink)

Show all headers | View raw


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]]
 
   Tony

]-> -----Original Message-----
]-> From: pooleman133 [mailto:poolebc221@gmail.com]
]-> Sent: 26 October 2011 22:39
]-> To: mathgroup@smc.vnet.net
]-> 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
head
]-> it gives me a bad count. The code I am using is listed below any help
would
]-> be greatly appreciated.
]-> 
]-> y[n_] := Block[{g, s},
]-> 
]-> 
]->   g := RandomChoice[{"head", "tail"}, n];
]->   s := Count[g, "head"];
]->   {g, s}
]->   ]


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


Thread

Re: Coin Toss Simulation "Tony Harker" <a.harker@ucl.ac.uk> - 2011-10-27 10:28 +0000

csiph-web