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.
This doesn't work for larger
n
becausefactorial(n)
is too big:This should return 200, but the computer only sees that you are trying to divide
Inf
byInf
: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 versionlfactorial
to avoid running into numbers your computer can't store.Edit: Added
lfactorial
recommendation from @MrFlick's comment