Repository navigation
fix: mod of two negative bigints - #3684
Conversation
mod(x, y) is documented as floored modulo (x - y * floor(x / y)), whose result takes the sign of the divisor, and the number, BigNumber and Fraction implementations all follow it. The bigint handler branched on the sign of the dividend and otherwise returned JavaScript's `%`, which takes the sign of the dividend, so for a negative divisor it produced the wrong sign: mod(10n, -4n) returned 2n instead of -2n. Compute the floored remainder for bigints directly, correcting the `%` result when its sign disagrees with the divisor, so bigint matches the other numeric types for every sign combination.
lbesecker195
left a comment
There was a problem hiding this comment.
I checked the new bigint branch against x - y * floor(x / y) for 28 sign combinations of dividend and divisor: zero mismatches. This brings bigint in line with the number, BigNumber, and Fraction implementations. LGTM.
|
I believe this was resolved by #3710. If you think there are any remaining difficulties in develop with respect to the issue addressed here, or any tests that should be in place that aren't, please post here. Otherwise please close this PR. Thanks so much. |
…egative-divisor # Conflicts: # src/function/arithmetic/mod.js
|
#3710 fixed
I merged If you would rather fix it differently, I am fine closing this. |
|
No this is fine. Added a comment for the slightly arcane final formula in _modBigint -- please check that you agree with the comment. Merging. |
mod(x, y)is floored modulo, but_modBigintreturns an out-of-range result when both arguments are negative:mod(-10n, -4n)andmod(-10, -4n)are-6n, whilemod(-10, -4)is-2.invmodon bigints inherits this:invmod(2n, -7n)is-10n, whileinvmod(2, -7)is-3._modBigintnow addsyonly when the remainder and the divisor have different signs.Three tests in
mod.test.jsandinvmod.test.jscover this. They fail ondevelopand pass with the fix.AI use: This PR is AI-assisted. An AI coding assistant found the remaining cases, wrote the change and the tests, and ran them. I reviewed the change and the results, and I decided to open it.