2
$\begingroup$

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).

Edit:

Select[expr,NumericQ]
(*0. + 10.8327 I*)

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

$\endgroup$
4
  • 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

3
$\begingroup$

UPDATE

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

extractCoefficient=
Function[input,Activate[HoldForm/@Select[Flatten[Inactivate[input]//.Inactive[Times]->List//.Inactive[Power][a__]:>Thread[Inactive[Power][a]]],NumericQ[Activate[#]]&]]/.List->Inactive[Times],HoldFirst];

Result:

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

OLD CODE

Following function, albeit ugly, does the job.

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

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]
$\endgroup$
2
  • $\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.