Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
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.


Comment on Re^2: Monte Carlo - Coin Toss
Select or Download Code
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.

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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2014-09-23 01:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (210 votes), past polls