Subject: | binomial with negative n |
Math::BigInt does not implement the standard extension of binomials to negative arguments. See:
http://mathworld.wolfram.com/BinomialCoefficient.html
which is what Pari, Mathematica, GMP, and the development version of Math::Prime::Util implement.
$ perl -MMath::Pari=binomial -E 'say binomial(-10,5)'
-2002
$ perl -MMath::GMPz=:mpz -E 'my $n = Rmpz_init(); Rmpz_bin_ui($n, Math::GMPz->new(-10), Math::GMPz->new(5)); say $n'
-2002
http://www.wolframalpha.com/input/?i=Binomial[-10%2C5]
Result: -2002
In contrast:
$ perl -Mbigint=lib,Calc -E 'my $n = -10; say $n->bnok(5)'
-252
$ perl -Mbigint=lib,GMP -E 'my $n = -10; say $n->bnok(5)'
-252
$ perl -Mbigint=lib,Pari -E 'my $n = -10; say $n->bnok(5)'
14
The last entry is especially troubling. The Calc and GMP backends have _nok routines, Pari does not. Interestingly, GMP and Pari both have binomial built in, but neither backend uses the library function.
The following, put right after the inf/NaN checks and before the k > n checks, will give the correct results for these examples. It has not been tested extensively.
return $self->bnok(-$x+$y-1,$y,@r) * (1,-1)[$CALC->_is_odd($y->{value})]
if $x->{sign} =~ /^-/;