With the way that Perl chooses to handle numbers, you cannot represent large numbers in native Perl. (Other languages do not necessarily have this limitation.) Anyways a correction and a suggestion.

The correction is that you misunderstood what I suggested would be more accurate. Try this line for the log(n!):

my $log_nfact = $n * log ($n) - $n + 0.5 * (log(2*PI*$n + 1/3));
Try it, it should be better.

The suggestion is that your problem was about binomial probabilities. Rather than try to calculate the factorials and work with them directly, estimate the logs of the factorials and use them to calculate the log of n choose m. Only then use the exponential.

For n and m large enough you'll again run into problems with Perl's support for large numbers. But since the final number is more modest than the intermediate factorials, you'll be able to go much farther. And when you get beyond what Perl can handle natively, if you have the log, you can divide it by log(10) to get the log base 10, and now you can take the integer and fractional parts of that and readily convert your answer into scientific notation for display even though Perl's native scientific notation doesn't go that high.

And that latter strategy will work for any n and m that you're likely to encounter in practice.

Update: Fixed algebra per kvale's note. (What I get for posting fast on a late night.)


In reply to Re: Stirling Approx to N! for large Number? by tilly
in thread Stirling Approx to N! for large Number? by monkfan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.