Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a function that returns results that always can be represented as $p+q\,\pi^2+r\ln2+s\ln^22+t\sqrt2$ where $p,q,r,s,t\in\mathbb Q$. But the actual Mathematica expression returned not always in exactly this form, e.g. it can be

1/Sqrt[2] + 1/54 (34 - 3 π^2 + (-8 + Log[8]) Log[64])

It's not difficult to extract rational coefficients from this expression manually, but I need to process hundreds of expressions, so I want to make this process automated. How can I do this?

share|improve this question

closed as off-topic by Mr.Wizard Aug 15 at 17:11

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question cannot be answered without additional information. Questions on problems in code must describe the specific problem and include valid code to reproduce it. Any data used for programming examples should be embedded in the question or code to generate the (fake) data must be included." – Mr.Wizard
If this question can be reworded to fit the rules in the help center, please edit the question.

Please include multiple examples on which to test our methods. –  Mr.Wizard Aug 9 at 18:20
I recommend using PowerExpand see e.g. How can I simplify log(512) to 9log(2)?. It is faster than appropriate useage of FullSimplify or Simplify with ComplexityFunction. Try e.g. Expand @ PowerExpand[ 1/Sqrt[2] + 1/54 (34 - 3 \[Pi]^2 + (-8 + Log[8]) Log[64])]. It yields 17/27 + 1/Sqrt[2] - \[Pi]^2/18 - (8 Log[2])/9 + Log[2]^2/3. –  Artes Aug 10 at 16:42

1 Answer 1

Probably you will have to adapt my basic idea to your special needs.

mem = 1/Sqrt[2] + 1/54 (34 - 3 π^2 + (-8 + Log[8]) Log[64]) // 
   ExpandAll // Apply[List, #] &
{mem[[1]], mem[[2]]/Sqrt[2], mem[[3]]/Pi^2, mem[[4]]/Log[2], 
  mem[[5]]/Log[2]^2} // FullSimplify

a possible adaption

The key is: after ExpandAll the summands are sorted in the same order, containing the factors:

{1, Sqrt[2], Pi^2, Log[2], Log[2]^2}

here a function, which calculates the rational coefficients in your desired order:

pqrstCoeff = 
  Function[# // ExpandAll // Apply[List, #] & // 
      Divide[#, {1, Sqrt[2], Pi^2, Log[2], Log[2]^2}] & // 
     FullSimplify // Part[#, {1, 3, 4, 5, 2}] &];

and you may verify:

givenExpression = 
 1/Sqrt[2] + 1/54 (34 - 3 π^2 + (-8 + Log[8]) Log[64])
pqrst = {p, q, r, s, t} = givenExpression // pqrstCoeff

pqrst // Element[#, Rationals] &

with results:

{17/27, -(1/18), -(8/9), 1/3, 1/2}

share|improve this answer

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