6

Is this just me being stupid, or is this a known bug in Mathematica?

Coefficient[2 x + 2 y, x + y]

gives 0, while

Coefficient[2(x + y), x + y]

gives 2. The documentation says that it should work whenever the expression is expanded or not...

I can see the problem with Coefficient[x-y, x + y] but if all coefficients in expr and form are positive, then surely there is a well-defined largest number k, such that expr-k*form have non-negative coefficients? And this is what I'd expect.

Coefficient[expr,form] 

EDIT: In my case,

PolynomialReduce[expr,{form},vars][[1,1]]

does the thing I want. This computes k such that expr-k form is minimal in some sense.

Per Alexandersson
  • 2,469
  • 15
  • 19

1 Answers1

4

[I deleted my first answer because I somehow made a mistake testing the OP's original input.]

[Edit: The OP substituted a simpler example, so I deleted my analysis of the original one and substituted another simpler but similar example.]

One question has to do with how Coefficient[expr, form] matches terms of expr to a given form. For instance, the "form" of 3x + 3y is quite a bit different than x + y, which has no coefficients multiplying the variables. Indeed, on this example (somewhat like the original one), observe the following:

poly = (x + y + z + 2)^2;
poly2 = x + y;

Coefficient[poly + poly2, poly2]
Coefficient[poly + poly2 // Expand, poly2]
Coefficient[poly + poly2, 2 poly2]
1
0
5/2 + z

So 2 Coefficient[poly + poly2, 2 poly2] gives the correct answer, which is an awkward workaround.

But here's an even stranger behavior that seems just plain wrong to me:

Coefficient[4 x + 2 y + 2 z, 2 (x/2 + y/2)]
Coefficient[4 x + 2 y + 2 z, x + y]
4
0

In the first form, it seems the second term is ignored, even if it's nonsense:

Coefficient[4 x + 2 y + 2 z, 2 (x + t)]
Coefficient[4 x + 2 y + 2 z, 2 (x + Plot[Sin[x], {x, 0, 2 Pi}])]
2
2

In Coefficient[expr, form], there seems to be something odd in the way form matches terms of expr when form involves Plus. I have not found an example in the reference manual in which form simplifies to a sum of terms. Perhaps it's not intended to be used this way.

Michael E2
  • 235,386
  • 17
  • 334
  • 747