Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re^2: Monte Carlo - Coin Toss

by jwkrahn (Abbot)
on Mar 12, 2011 at 01:22 UTC ( [id://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 (Canon) 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 (Patriarch) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://892772]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-19 10:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found