Skip to content

CollectLikeTerms fails on the very example its documentation cites #855

Description

@Rafael-SOWNet

Split out of #852, where it was found and deliberately not folded in. Pre-existing, not a 2.0 regression — reproduced on master before that change and after it.

The case

CollectLikeTerms carries this doc comment:

Adds up the terms of an expanded sum that differ only by a numeric factor, so that expanding actually finishes: (x+1)^2 * (x+1)^2 multiplied out gives sixteen terms, of which only five are distinct.

That exact expression is the one it does not finish:

(x+1)^2 * (x+1)^2         ->  1 + 4x + 2x^2 + 4x^2 + 4x^3 + x^4     six terms
(x+1)^4                   ->  1 + 4x + 6x^2 + 4x^3 + x^4            five, correct
(x+1)*(x+1)*(x+1)*(x+1)   ->  x^4 + 4x^3 + 6x^2 + 4x + 1            five, correct
(x+1)^2*(x+2)^2           ->  4 + 12x + 13x^2 + 6x^3 + x^4          five, correct

2x^2 + 4x^2 is left standing. The answer is correct — the coefficients sum to 16, so no term is lost or duplicated — but the collection that the method exists to perform did not happen, and the result is one term longer than it should be.

Identical at Expand(1), Expand(2) and Expand(3), so it is not a question of passes.

Why it is worth chasing

The three neighbouring forms all collect correctly, so whatever is different about the same base squared, multiplied by itself is narrow. Two terms that both mean x^2 are landing under different monomial keys, and the key is built from the exponent dictionary, so the exponents are being reached by two routes that do not agree — most likely one term arriving as x^2 and another as x * x and the two not reducing to the same key.

Anything that reduces to a monomial by two different routes is a candidate for the same fault, so the fix is probably worth more than this one expression.

Deliberately not fixed for 2.0

Recommending this does not block the release. It produces a correct answer that is one term longer than it should be, which is a quality defect rather than a wrong answer, and CollectLikeTerms sits in the middle of expansion and simplification — not somewhere to make a hurried change days before a major version. It wants a proper look and a test over the routes into a monomial key, not a patch.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions