Friday, May 27, 2016

What is the difference between factorial and lfactorial in R programming?

Factorial computes the factorial of a number. Given a number n it computes n! (n factorial). You can follow this after launching the R Gui. 5! is same as 5x4x3x2x1
---------------
> factorial(5)
[1] 120
---------------
factorial in R programming is also applicable to non-integers.
------
> factorial(5.5)
[1] 287.8853
-------------
How does R programming calculates factorial. It is calculated in the most efficient manner using the Gamma function.
factorial(x)=gamma(x+1)

In implementation to calculate factorial R calculates the gamma
factorial(5)=gamma(5+1)
------
> gamma(5+1)
[1] 120  - This is same as factorial(5)
----
What about lfactorial in R programming?

The definition of lfactorial (http://www.stata.com/manuals13/m-5factorial.pdf) is ;
lfactorial(n) is log(factorial(n))
-----
> lfactorial(5)
[1] 4.787492
> log(factorial(5))
[1] 4.787492
------------
Another interesting tip is you can use factorial function presenting it with a list like factorial(c(5,4,3)) and not a number. It would then compute the factorial for each of the numbers. For example:
----
> factorial(c(5,4,3))
[1] 120  24   6
> factorial(c(5,4.3,2))
[1] 120.00000  38.07798   2.00000
> lfactorial(c(5,4,3))
[1] 4.787492 3.178054 1.791759
----------

No comments: