Skip to content

combinations(42,21) is not an integer #2413

@gwhitney

Description

@gwhitney

Currently math.combinations(42,21) returns 538257874439.99994. This of course can't be right, because the number of combinations must always be an integer. And in fact the actual value is 538257874440. While I recognize that by default mathjs computes with JavaScript numbers, and they lose precision and can't encode individual large integers distinctly, this answer is still well below the value of MAX_SAFE_INTEGER by at least 4 orders of magnitude. So mathjs should be able to get this binomial exactly correct. (The non-integer value was actually disrupting some calculations I was doing with the first several catalan numbers, which quite reasonably assumed that they would all be integers.)

The difficulty in the implementation in src/plain/number/combinations.js is that all of the numbers in the numerator are multiplied, and then divided by the product of all of the numbers in the denominator. The intermediate results can easily overflow the safe integer range even when the result very much does not. An approach that balances multiplication by divisions whenever they are safe to perform (i.e., leave no remainder) should greatly extend the range of accurate values of the combinations() function on ordinary JavaScript numbers.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions