From c98d75b51fb5a3896583719b9a31b653bd1e0c2c Mon Sep 17 00:00:00 2001 From: apoorva-01 Date: Thu, 2 Jul 2026 22:57:17 +0530 Subject: [PATCH] Fix adding a BigNumber scalar to a number-datatype matrix matAlgo14xDs forced the scalar into the matrix's datatype, so a BigNumber plus a `number` matrix threw instead of promoting. Take that fast path only when the scalar converts, otherwise fall back to the generic callback. --- src/type/matrix/utils/matAlgo14xDs.js | 19 +++++++++++++------ .../function/arithmetic/add.test.js | 7 +++++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/type/matrix/utils/matAlgo14xDs.js b/src/type/matrix/utils/matAlgo14xDs.js index 342b2b19d9..463cb6233e 100644 --- a/src/type/matrix/utils/matAlgo14xDs.js +++ b/src/type/matrix/utils/matAlgo14xDs.js @@ -33,12 +33,19 @@ export const createMatAlgo14xDs = /* #__PURE__ */ factory(name, dependencies, ({ // process data types if (typeof adt === 'string') { - // datatype - dt = adt - // convert b to the same datatype - b = typed.convert(b, dt) - // callback - cf = typed.find(callback, [dt, dt]) + // Take the datatype fast-path only when the scalar converts into the + // matrix's datatype. When it cannot (e.g. a BigNumber scalar and a + // `number` matrix), fall through to the generic callback so the values + // promote as usual instead of throwing on the conversion. + let converted + try { + converted = typed.convert(b, adt) + } catch {} + if (converted !== undefined) { + b = converted + dt = adt + cf = typed.find(callback, [dt, dt]) + } } // populate cdata, iterate through dimensions diff --git a/test/unit-tests/function/arithmetic/add.test.js b/test/unit-tests/function/arithmetic/add.test.js index aa5c385bf3..0c6b17dc27 100644 --- a/test/unit-tests/function/arithmetic/add.test.js +++ b/test/unit-tests/function/arithmetic/add.test.js @@ -123,6 +123,13 @@ describe('add', function () { assert.deepStrictEqual(a4.size(), [2]) assert.deepStrictEqual(a4.valueOf(), [math.bignumber(8), math.bignumber(10)]) }) + + it('should promote when a scalar does not fit the matrix datatype (#3612)', function () { + const a = math.matrix([[1, 2]], 'dense', 'number') + const expected = math.matrix([[math.bignumber(4), math.bignumber(5)]]) + assert.deepStrictEqual(add(a, math.bignumber(3)), expected) + assert.deepStrictEqual(add(math.bignumber(3), a), expected) + }) }) describe('SparseMatrix', function () {