in reply to Operations with Extremely Large Numbers

The problem is that your are trying to use the exlusive-or operator ^ to perform exponentiation **.

This works:

use Math::Trig; use bignum; sub factorial { my $n = @_; my $root = sqrt($n*2*pi); my $exp = ($n/exp(1)) ** $n; my $result =$root*$exp; return $result; } my $b = 2032597; my $r = Math::BigInt->new(factorial($b)); print "b is $b\n"; print "the calculated result is $r\n";

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: Operations with Extremely Large Numbers
by BrowserUk (Patriarch) on Nov 09, 2011 at 18:14 UTC

    A further thought. If these calculations are in anyway time-critical.

    In almost every formula I've ever encountered that uses huge factorials -- usually probability calculations of one form or another -- there are usually (at least) two factorial (or factorial derived) terms that eventually are divided one by the other so bringing the silly numbers back into the realms of rationality.

    So you tend to have formulae something like:

    r = n! / (n - m)!

    Ostensibly, the calculation goes like this:

    n = 1e9 m = 4 r = ( 1 * 2 * 3 ... 999999999 * 1000000000 ) / ( 5 * 6 * 7 ... 999999999 * 1000000000 )

    Which using arbitrary precision can take long time (and a large amount of memory) to calculate.

    But with cursory inspection it is easy to see that the result is just 1/ ( 1* 2 * 3 * 4 ) == 1/24 == 0.041666666666666666666666666666667 .

    If your application requires the calculation of large numbers of these types of formulae, and timeliness is of any consideration, it makes sense to avoid the huge numbers by deferring the actual math until you've performed some "cancelling out".

    In most cases, the avoidance of arbitrary precision more than compensates for the extra effort and care required.

      Thanks BrowserUk. I literally bonked myself in the head after reading this. I'm going to try giving careful consideration to the overall formula to see if there's mathematical cancellations.

      Small correction, 1e9! / (1e9-4)! would not be 1/(1*2*3*4) but 1/(999999997*999999998*999999999*1000000000)

      And you are probably thinking about the binomial coefficient, which is n! / ( k! * (n-k)! )