How to compute the natural logarithm of a factorial: large numbers

Hello all,

Is there a function in C to compute the natural logarithm of a factorial, say, log(factorial(646))?

In most statistical packages, such as R, the factorial can be computed up to 177 (e.g. factorial(177) or so. But for statistical purposes, all formulae can be worked in the logarithm scale. As a result, these packages compute very large lnfactorials, such as lnfactorial(854511124).

I will be really grateful for any tips.

[it is important to note that I do not need approximations, since the lnfactorials will be used to compute statistical estimates that need to be extremely precise up to the 7th decimal place).

Cheers!

Tiago

"int y" should be declared "double y" ?

Hello,

I tried the code below to verify the solution... I got the following error from my compiler:

"more than one instance of overloaded function "log" matches the argument list"

In the function definition, I noticed the "int y" which is used in " z = log( y ) + z ; " and when I changed the variable "y" to a type double, the code below compiled with no errors.

I'm using Microsoft VS 2010 compiler, and I have my doubts whether it's ANSI compliant in the first place. Especially when it comes to mathematical work. So if this is the case, please accept my apology in advance.

I'm very interested in seeing how this program works, is the reason why I tried it in the first place. Cheers!

Quote:

Originally Posted by

**TiagoPereira**
I guess I have solved this question with a simple function by noting the additive effects on the logarithm scale:

Code:

double lnfactorial( int a)

{

int y;

double z;

if (a == 1)

return 0;

else

{

z = 0;

for (y = 2; y<=a; y++ )

z = log(y)+z;

return z;

}

}

asymptotic expression if you don't need high precision

Any math handbook or google can tell you the following formula for large N

ln(N!) \approx [ N ln(N) ] -N

Try that with your number.