factorial - R: How can I calculate large numbers in n-choose-k? -


this question has answer here:

for class assignment, need create function calculates n choose k. did that, , works fine small numbers (e.g. 6 choose 2), i'm supposed work 200 choose 50, naturally doesn't. answer large , r outputs nan or inf, saying:

> q5(200, 50) [1] "nan" warning message: in factorial(n) : value out of range in 'gammafn' 

i tried using logs , exponents, doesn't cut it.

q5 <- function (n, k) {   answer <- log(exp( factorial(n) / ( (factorial(k)) * (factorial(n - k)) )))   paste0(answer) } 

the answer actual question r cannot show numbers cannot represent, , of terms in equation big represent. fails. there approximations factorial can used - work logarithms big lot slower.

the famous one, sterling's approximation, not accurate enough, ramanujan's approximation came rescue :)

ramanujan <- function(n){   n*log(n) - n + log(n*(1 + 4*n*(1+2*n)))/6 + log(pi)/2 }  nchoosek <- function(n,k){   factorial(n)/(factorial(k)*factorial(n-k)) }   bignchoosek <- function(n,k){   exp(ramanujan(n) - ramanujan(k) - ramanujan(n-k)) }  nchoosek(20,5) # [1] 15504  bignchoosek(20,5) # [1] 15504.06   bignchoosek(200,50) # [1] 4.538584e+47 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -