Skip to content

Commit

Permalink
fix #3087: extend function mod with support for negative divisors i…
Browse files Browse the repository at this point in the history
…n when using `BigNumber` or `Fraction`
  • Loading branch information
josdejong committed Nov 8, 2023
1 parent 76c4811 commit 8679c07
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 12 deletions.
6 changes: 6 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
# History


# unpublished changes since 12.0.0

- Fix #3087: extend function `mod` with support for negative divisors in when
using `BigNumber` or `Fraction`.


# 2023-10-26, 12.0.0

Breaking changes:
Expand Down
10 changes: 2 additions & 8 deletions src/function/arithmetic/mod.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,11 @@ export const createMod = /* #__PURE__ */ factory(name, dependencies, ({ typed, c
'number, number': _modNumber,

'BigNumber, BigNumber': function (x, y) {
if (y.isNeg()) {
throw new Error('Cannot calculate mod for a negative divisor')
} return y.isZero() ? x : x.mod(y)
return y.isZero() ? x : x.sub(y.mul(floor(x.div(y))))
},

'Fraction, Fraction': function (x, y) {
if (y.compare(0) < 0) {
throw new Error('Cannot calculate mod for a negative divisor')
}
// Workaround suggested in Fraction.js library to calculate correct modulo for negative dividend
return x.compare(0) >= 0 ? x.mod(y) : x.mod(y).add(y).mod(y)
return y.equals(0) ? x : x.sub(y.mul(floor(x.div(y))))
}
},
matrixAlgorithmSuite({
Expand Down
8 changes: 4 additions & 4 deletions test/unit-tests/function/arithmetic/mod.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ describe('mod', function () {
assert.deepStrictEqual(mod(bignumber(-5), bignumber(3)), bignumber(1))
})

it('should throw an error if the divisor in modulus of bignumbers is negative', function () {
assert.throws(function () { mod(bignumber(10), bignumber(-4)) })
it('should calculate the modulus of bignumbers for a negative divisor', function () {
assert.deepStrictEqual(mod(bignumber(10), bignumber(-4)), bignumber(-2))
})

it('should calculate the modulus of mixed numbers and bignumbers', function () {
Expand Down Expand Up @@ -126,8 +126,8 @@ describe('mod', function () {
assert.strictEqual(mod(math.fraction(-5), math.fraction(3)).toString(), '1')
})

it('should throw an error if the divosor in modulus of fractions is negative', function () {
assert.throws(function () { mod(math.fraction(10), math.fraction(-4)) })
it('should calculate the modulus of fractions for a negative divisor', function () {
assert.strictEqual(mod(math.fraction(10), math.fraction(-4)).toString(), '-2')
})

it('should calculate modulus of mixed fractions and numbers', function () {
Expand Down

0 comments on commit 8679c07

Please sign in to comment.