TransWikia.com

Extracting a product of factors from an expression in unevaluated form

Mathematica Asked by Subho on June 2, 2021

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?

One Answer

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]

Answered by Soner on June 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP