Suppose I have an expression like so:

$\qquad {\rm expr}=2\,i\,{\rm Gamma}(4)\,\pi\, 9.93 f(x)\,g(y) \frac{h(x, 4y)^3}{11 q}$

What is best (most succinct) way to extract out only the product of numbers?

The answer I expect is:

$\qquad 2\,i\,{\rm Gamma}(4)\,\pi\,9.93\,\frac{1}{11}$

I would want this the code to work for as generic an expression as possible in the sense that it should pick all the numbers(Real or Complex or Transcendental or Special Constants).


(*0. + 10.8327 I*)

almost seems to work but not quite as it performs the product and simplifies. Any way to HoldForm here?

  • 2
    $\begingroup$ Look up FactorTerms[]. $\endgroup$ Mar 11, 2018 at 18:09
  • $\begingroup$ @J.M. Any suggestions following the edit? Wasn't able to make much out of FactorTerms[] $\endgroup$
    – Subho
    Mar 13, 2018 at 19:05
  • $\begingroup$ Well, did you look at what expr looked like after storing that expression? Why were you expecting that the arithmetic won't be performed? $\endgroup$ Mar 13, 2018 at 19:10
  • $\begingroup$ @J.M. Sure, the expression has been evaluated in the assignment itself. I wanted to find a way to extract out all the numeric factors in the form they appear in the expression. Is there a way to do that? So, if my input expression was the one I wrote as in the example, the output should have the unevaluated form of the numeric subexpression. $\endgroup$
    – Subho
    Mar 13, 2018 at 19:42

1 Answer 1



Following function is more efficient and it captures terms in the denominator:



In[364]:= extractCoefficient[2I Gamma[4] Pi 9.93 f[x] g[y] h[x,4 y]^3/(11q)]
Out[364]= 2*I*Gamma[4]*\[Pi]*9.93*1/11


Following function, albeit ugly, does the job.

    Function[input,  HoldForm@@((Times@@Select[Thread[Replace[Hold[input],Hold[Times[a_,b__]]:>Hold[{a,b}]]],(NumericQ@@#&)])
    //.Hold[a_]Hold[b_]:> Hold[a b])

Your case:

In[152]:= extractCoefficient[2I Gamma[4] Pi 9.93 f[x] g[y] h[x,4 y]^3/(11q)]

Out[152]= (((2 9.93) I) \[Pi]) Gamma[4]
  • $\begingroup$ It misses the $1/11$ factor $\endgroup$
    – Subho
    Mar 14, 2018 at 8:33
  • $\begingroup$ Corrected it now. $\endgroup$ Mar 14, 2018 at 8:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.