Skip to content

fix: allow zero values in multinomial#3664

Open
chatman-media wants to merge 1 commit into
josdejong:developfrom
chatman-media:fix/multinomial-allow-zero
Open

fix: allow zero values in multinomial#3664
chatman-media wants to merge 1 commit into
josdejong:developfrom
chatman-media:fix/multinomial-allow-zero

Conversation

@chatman-media

Copy link
Copy Markdown

What

multinomial threw a TypeError for any input array containing a zero:

math.multinomial([2, 0, 1]) // TypeError: Positive integer value expected in function multinomial
math.multinomial([3, 0])    // TypeError
math.multinomial([0])       // TypeError

A zero count is mathematically valid. The multinomial coefficient is

multinomial([k₁, …, kₘ]) = (Σ kᵢ)! / ∏ (kᵢ!)

and since 0! = 1, a zero part simply contributes a factor of 1. The expected values are:

call correct value
multinomial([2, 0, 1]) 3
multinomial([3, 0]) 1
multinomial([0]) 1
multinomial([0, 4, 4]) 70

(verified against Python's math.factorial.)

Why it's a bug (inconsistency)

The multinomial coefficient is the standard generalization of the binomial coefficient, and multinomial([k, n - k]) should equal combinations(n, k). But:

math.combinations(5, 5)   // 1   ✅
math.multinomial([5, 0])  // TypeError ❌  (same quantity!)

combinations (both the number and BigNumber paths), combinationsWithRep, and factorial all accept non-negative integers (their "positive integer" checks use >= 0). Only multinomial rejected zero, because it validated with !isPositive(ai) and isPositive(0) === false.

Fix

Reject only negatives (isNegative(ai)) instead of non-positives (!isPositive(ai)); the existing isInteger check still rejects non-integers. isNegative(0) is false for number, BigNumber, bigint, and Fraction, so a zero now passes while negatives and non-integers still throw. Also fixes the doc-comment typo (every ai <= 0every ai >= 0).

Tests

  • Added a test covering zero parts for both number and BigNumber, including the multinomial([k, n - k]) === combinations(n, k) identity.
  • Verified it fails without the source change (with the exact TypeError) and passes with it.
  • Full suite green: 6653 passing. ESLint clean.

multinomial threw a TypeError on any array containing a zero, e.g.
multinomial([2, 0, 1]). A zero count is mathematically valid since
0! = 1, and the multinomial coefficient is the standard generalization
of the binomial coefficient: multinomial([k, n - k]) === combinations(n, k).

The validation rejected zero via !isPositive(ai) (isPositive(0) is
false). Reject only negatives with isNegative(ai) instead, matching the
non-negative-integer semantics already used by combinations, factorial,
and combinationsWithRep. Also fix the doc comment typo (ai <= 0 -> ai >= 0).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant