Auto-substitute complex term to ease numeric evaluation
I have a very large symbolic term (mainly composed of sums, products and divisions) and, using substitutions, I want to reformulate it in a way that avoids repetitions and thus can be evaluated using less arithmetic operations.
For example, if I have a term like
X = (d*(a-b)/(1 + a-b))^2 + d*(a-b)/(1 + a-b) + exp(d*(a-b)/(1 + a-b)) + a-b,
I want a function that returns something like:
S1 = a-b
S2 = d*S1/(1+S1)
X = S2^2 + S2 + exp(S2) + S1
Giving me instructions how to more efficiently calculate X: First calculate S1, then S2 using S1 and finally X using S1 and S2.
My actual problem is much nastier and I do not need optimal or near-optimal results, but any way of automatising such substitutions.