Search code examples
rerror-handlingbinomial-coefficients

R: error when trying to write an equivalent function n choose k


I'm taking the class of introduction for R programming.

we were asked to write a function that will be the same as n choose k:

choose(n, k)

we were asked to check if the function works by running n = 200, k = 50.

I wrote the following code:

    select_k <- function(n, k){
  sr <- c(log10(log10((factorial(n-1)/factorial(k-1)*factorial(n-k-2)))*(n/k)))
  return(sr)
}

as select_k is supposed to be the " n choose k".

my function works with values such as: 100 choose 25, but it doesn't work with greater values, like n = 200, k = = 50.

select_k( n = 200, k = 50)
[1] NaN
Warning message:
In factorial(n) : value out of range in 'gammafn'

I have no idea what else can be done to fix that.


Solution

  • This doesn't work for larger n because factorial(n) is too big:

    > factorial(199)
    [1] Inf
    Warning message:
    In factorial(199) : value out of range in 'gammafn'
    

    This should return 200, but the computer only sees that you are trying to divide Inf by Inf:

    > factorial(200)/factorial(199)
    [1] NaN
    Warning messages:
    1: In factorial(200) : value out of range in 'gammafn'
    2: In factorial(199) : value out of range in 'gammafn'
    

    Obviously a lot of the multiplications in "n choose k" cancel out, so you'll need to avoid using regular factorial and only multiply the numbers that don't cancel out (?prod might be useful for you). Or (probably better) use the log version lfactorial to avoid running into numbers your computer can't store.

    Edit: Added lfactorial recommendation from @MrFlick's comment