Search code examples
rrecursionfactorial

the largest n that you can use in recursion factorial in R


I have a recursion factorial

recursive.factorial <- function(x) {
    if (x == 0)    return (1)
    else           return (x * recursive.factorial(x-1))
}

Just curious what can be the largest x here in my recursive.factorial v.s the build-int factorial() function in R? is there a way to check with that


Solution

  • The bit-span of computer numeric values seems much more likely to be the problem than the "computer memory" by which I am assuming you meant the address space of RAM. The largest value for an integer that can be represented without approximation in R (and any software package using the usual IEEE standard) is 2^53 - 1. There are other packages (some of them available as R packages) that can support arbitrary precision numerics. The ?Recall functions is a more stable methods of doing recursion, although it is not optimized in R. The integer.max is set at the precison obtainable with 2 bytes:

     2^32-1
    [1] 4294967295
    

    And the more recently introduced "long integers" max out at the limits of the mantissa of floating point "doubles".

    > 2^53-1
    [1] 9.007199e+15
    > print( 2^53-1, digits=18)
    [1] 9007199254740991
    

    So as soon as you get a value of factorial(n) that is larger than that limit you only get an approximation and when you exceed the limits of the exponentiation for a "double" numeric, you get "Inf". My version of factorial seems to have the same breaking point as yours:

    > fact <- function(n)
    +    if(n==0) { 1} else{ (n) *Recall(n-1)}
    > fact (170)
    [1] 7.257416e+306
    > fact (171)
    [1] Inf
    

    Here's another way of thinking about calculating factorial:

    > exp( sum(log(1:15)))
    [1] 1.307674e+12
    > factorial(15)
    [1] 1.307674e+12
    

    The "Stirling's approximation" is often used to speed up calculations of factorial. For more accurate values you can install either the gmp or the Rmpfr packages.