I am new to Mathematica, and am having trouble achieving something very simple to explain. I would like Mathematica to reformulate my input, replacing similar terms in a formula with variables, so that no computation appears twice in the formula. Something like this:

In[1] = XXXXXXX[(a+b*t)*t/(b*t+q) + (b*t+q)*t/(a+b*t)]
Out[1] = v1*t/v2 + v2*t/v1  with {v0 = b*t, v1 = (a+v0), v2=(v0+q)}

Thanks for your help


You may be looking for Experimental`OptimizeExpression. It produces precisely the output you describe.

In[50]:= Experimental`OptimizeExpression[(a + b*t)*t/(b*t + q) + (b*t + q)*t/(a + b*t)]

Out[50]= Experimental`OptimizedExpression[
 Block[{Compile`$1, Compile`$2, Compile`$3}, 
  Compile`$1 = b t; 
  Compile`$2 = a + Compile`$1; 
  Compile`$3 = q + Compile`$1; 
  (t Compile`$2)/Compile`$3 + (t Compile`$3)/Compile`$2]]

This function is meant for minimizing the number of arithmetic operations to compute an expression. The goal is performance optimization. Compile uses it internally.

I don't find it useful for symbolic computation, but since its output is exactly what you were asking for, I thought it should be in an answer.

Also check its options:


{ExcludedForms -> {}, "ExternalForms" -> {}, "InertForms" -> {}, 
 "OptimizationLevel" -> 1, "OptimizationSymbol" -> Compile`$}

You may want to set "OptimizationSymbol" -> v.

See also:


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