Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/function/algebra/simplify.js
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,11 @@ export const createSimplify = /* #__PURE__ */ factory(name, dependencies, (
s: '(n1*n2)^(-1) -> n2^(-1) * n1^(-1)',
assuming: { multiply: { commutative: false } }
},
// Distributing a power over the unit factor that 'n/n1 -> n*n1^-1' leaves
// behind produces 1^n. Without this rule that factor is never eliminated
// and accumulates a larger exponent on every pass, so simplification of a
// symbolic power of a reciprocal never converges. See #3693.
{ l: '1^n', r: '1' },

// expand nested exponentiation
{
Expand Down
31 changes: 31 additions & 0 deletions test/unit-tests/function/algebra/simplify.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,36 @@ describe('simplify', function () {
simplifyAndCompare('8 - n', '8 - n')
})

it('should remove unit factors raised to a power', function () {
simplifyAndCompare('1^x', '1')
simplifyAndCompare('1^(2*x)', '1')
simplifyAndCompare('1^x*y', 'y')
simplifyAndCompare('(1*x)^y', 'x^y')
simplifyAndCompare('(x/2)^y', 'x^y/2^y')
})

it('should terminate when simplifying symbolic powers of reciprocals', function () {
const expressions = [
['(1/(x*(y-1)))^(1/(y-1))', '(1/x/(y-1))^(1/(y-1))'],
['(1/(x*y))^z', '(1/x/y)^z'],
['(2/(x*y))^z', '2^z*(1/x/y)^z'],
['(1/(2*x))^y', '(1/2/x)^y'],
['(1/(x*y*z))^w', '(1/y/z/x)^w']
]
for (const [expression, expected] of expressions) {
let passes = 0
const rules = [node => {
// Fail a non-terminating rule cycle without hanging the test runner.
assert.ok(++passes < 20, 'Simplification did not converge: ' + expression)
return node
}, ...math.simplify.rules]
const simplified = math.simplify(expression, rules)
assert.strictEqual(simplified.toString(), math.parse(expected).toString())
const scope = { x: 2, y: 3, z: 0.5, w: 1.5 }
assert.ok(Math.abs(simplified.evaluate(scope) - math.evaluate(expression, scope)) < 1e-14)
}
})

it('should handle non-existing functions like a pro', function () {
simplifyAndCompare('foo(x)', 'foo(x)')
simplifyAndCompare('foo(1)', 'foo(1)')
Expand Down Expand Up @@ -466,6 +496,7 @@ describe('simplify', function () {
simplifyAndCompare('x*y*x^(-1)', 'x*y*x^(-1)', {}, optsNCM)
simplifyAndCompare('x*y/x', 'x*y*x^(-1)', {}, optsNCM)
simplifyAndCompare('x*y*(1/x)', 'x*y*x^(-1)', {}, optsNCM)
simplifyAndCompare('(1/(x*y))^z', '(y^(-1)*x^(-1))^z', {}, optsNCM)
// 'n+n->2*n' & 'n1*n3+n2*n3 -> (n1+n2)*n3' cannot apply for NCA
simplifyAndCompare('z+2+z', 'z+2+z', {}, optsNCA)
simplifyAndCompare('2*z+3+2*z', '2*z+3+2*z', {}, optsNCA)
Expand Down