Hi,
Following
tilly's posting
here. I attempted
to construct the code.
#!/usr/bin/perl -w
use strict;
my $h =8;
my $pure = factorial_pure($h);
my $stirling = factorial_stirling($h);
print "PURE : $pure\n";
print "STIRLING : $stirling\n"
#------Subroutines------------
sub factorial_stirling{
my $n = shift;
use constant PI => 4*atan2 (1,1);
use constant e => exp(1);
my $log_nfact =
$n * log ($n) - e* log($n) + 0.5 * (log(2*PI)+log($n));
# Below is Tilly's suggestion, with less accuracy
# $n * log ($n) - ($n) + (0.5 * (log(2+ log(PI))+log($n)));
return exp($log_nfact);
}
sub factorial_pure {
my ($n,$res) = (shift,1);
return undef unless $n>=0 and $n == int($n);
$res *= $n-- while $n>1;
return $res;
}
Stirling method indeed gives a faster result:
Rate pure stirling
pure 290034/s -- -30%
stirling 319835/s 16% --
With a reasonable approximation:
PURE : 40320
STIRLING : 417351.253768542
But when it comes to large N, e.g $h = 500. It began to fail.
I wonder if Tilly's suggestion is ever be possible,
i.e resorting to pure Perl arithmetic (no external module) yet able to handle large number in a fastway?
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.