There's more than one way to do things PerlMonks

### Re^2: Monte Carlo - Coin Toss

by jwkrahn (Monsignor)
 on Mar 12, 2011 at 01:22 UTC ( #892772=note: print w/replies, xml ) Need Help??

in reply to Re: Monte Carlo - Coin Toss
in thread Monte Carlo - Coin Toss

It is more idiomatic (and often simpler) to use Perl-style rather than C-style loops.

Yes, but it won't work if the numbers are too large for integers and have to use floating point.    Then only C style loops will work.

```my @collect = map 0, 0 .. NUM_TOSSES;

Why are you initializing @collect with NUM_TOSSES + 1 elements?

The idiomatic way to initialize @collect with NUM_TOSSES elements is usually:

```my @collect = ( 0 ) x NUM_TOSSES;
```for (\$i = 0; \$i < \$numTosses+1; \$i++) {

foreach my \$tailsCt ( 0 .. NUM_TOSSES )

You have an off-by-one error, it should be:

```foreach my \$tailsCt ( 0 .. NUM_TOSSES - 1 )

Update: oops, I misread the original code.

Replies are listed 'Best First'.
Re^3: Monte Carlo - Coin Toss
by johngg (Abbot) on Mar 12, 2011 at 12:38 UTC

Why are you initializing @collect with NUM_TOSSES + 1 elements?

The idiomatic way to initialize @collect with NUM_TOSSES elements is usually:

```my @collect = ( 0 ) x NUM_TOSSES;

As Eliya points out, 20 tosses could give 21 outcomes as regards the number of "tails" tossed, i.e. 0, 1, ... 19 or 20 so your way should be

```my @collect = ( 0 ) x ( NUM_TOSSES + 1 );

and I would agree that your way is perhaps more idiomatic. However, I felt that

```my @collect = map 0, 0 .. NUM_TOSSES;

better illustrated the relation between the numbers of tosses and outcomes. What do others think?

Cheers,

JohnGG

Re^3: Monte Carlo - Coin Toss
by Eliya (Vicar) on Mar 12, 2011 at 10:40 UTC
You have an off-by-one error, it should be: ...

No, 0 .. NUM_TOSSES is correct here, because adding up NUM_TOSSES (with a single result being 0 or 1) can potentially produce values ranging from zero to NUM_TOSSES.

Tossing a coin once can produce 0 or 1 tails;
tossing a coin twice can produce 0, 1 or 2 tails;
etc.

Re^3: Monte Carlo - Coin Toss
by ikegami (Pope) on Mar 12, 2011 at 08:18 UTC

Yes, but it won't work if the numbers are too large for integers and have to use floating point.

If 2 billion loop iterations are not enough for you, you can always nest loops to multiple the range.

Create A New User
Node Status?
node history
Node Type: note [id://892772]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (11)
As of 2018-06-18 16:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should cpanminus be part of the standard Perl release?

Results (110 votes). Check out past polls.

Notices?