# Get constant term with Coefficient for a non-polynomial

Take a nonlinear equation such as

exp = (x + 3)/4 + Exp[x] + 1 + (c + x)


Note that this is not a polynomial. Now, I want to extract the coefficients of this. A few are easy:

Coefficient[exp, x ] (* Correctly gives 5/4*)
Coefficient[exp, Exp[x] ] (* Correctly gives 1*)


But how can I extract the coefficient on the constant term?

I can't figure out how to write the "form" for the coefficient function to extract it. Note that treating it as a polyomial and asking for the 0th order will not work (e.g. Coefficient[exp, x,0] is not correct)

• Maybe Select[exp, FreeQ[x]]? – ilian May 13 '15 at 19:50
• Thanks. Seems close. Sadly, my expression is actually a little complicated, and Coefficient is doing some useful work. I just wrote a small variation of the expression which doesn't seem to be working with your Select approach. – jlperla May 13 '15 at 19:57
• Could you post the more complicated expression? – Virgil May 13 '15 at 20:03
• Select[ExpandAll[exp], FreeQ[x]] probably works for the revised exp -- don't know about the 'real' one, however. – ilian May 13 '15 at 20:23
• Thanks, simple enough! Should work for my current problem at least. – jlperla May 13 '15 at 21:47

You can use CoefficientList:

exp = (x + 3)/4 + Exp[x] + 1 + (c + x);
CoefficientList[exp, {x, Exp[x]}]
(*  {{7/4 + c, 1}, {5/4, 0}}  *)


Whether that is a convenient way depends on what you want to do with it. Following extracts the parts:

{{const, ExpC}, {xC, xExpC}} = %

• Thanks, I like it. Seems strange that you can't put in a constant pattern for the Coefficient function, though. – jlperla May 13 '15 at 21:51
• @jlperla I agree. One can do Fold[Coefficient[##, 0] &, exp, {x, Exp[x]}] but it's hardly more convenient. (Or maybe it is?) – Michael E2 May 13 '15 at 22:05
• Yeah, I think yours may be the winner. If I end up with many more coefficients (doing an undetermined coefficients solution to an ODE) your technique lets me extract from the top corner but also seems to tell me if I missed any terms since they would show up in the constant if I forgot them. – jlperla May 13 '15 at 22:07
• @jlperla Thanks. Another idiomatic alternative: exp /. Thread[Sort[{x, Exp[x]}, MemberQ] -> 0]. – Michael E2 May 13 '15 at 22:09

I usually do something like

expr = (x + 3)/4 + Exp[x] + 1 + (c + x);

xCoeff = Coefficient[expr, x];
expCoeff = Coefficient[expr, Exp[x]];
rest = Collect[expr - xCoeff*x - expCoeff*Exp[x], x];

{xCoeff, expCoeff, rest}

{5/4, 1, 7/4 + c}