The number of ways of choosing k objects from n, i.e. the binomial coefficient n!/(k!(n-k)!), is an integer when n and k are integers. How can I calculate this guaranteeing that the result is both correct and of integer type? The choose
function returns a double even with integer arguments:
> typeof(choose(4L, 2L))
[1] "double"
as does manual calculation, e.g. n-choose-2 = n(n-1)/2
typeof((4L * (4L - 1L)) / 2L)
[1] "double"
Of course I can coerce to an integer with as.integer()
but I'm nervous about machine precision:
> as.integer(3.999999999999999)
[1] 3
> as.integer(3.9999999999999999)
[1] 4
round()
(with the default digits=0
) rounds to the nearest integer, but returns a value of double type. If I could be certain that supplying an integer stored in double format to as.integer(round(...))
is guaranteed to round to the correct integer, never being tripped up by machine precision, then as.integer(round(choose(n, k)))
would be acceptable. Is this the case? Or is there an alternative to choose()
that will return an integer for integer arguments?