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

edit retag close merge delete

Sort by » oldest newest most voted

With some algebraic manipulation and the substitute command, you can partly get what you want. Of course, I think it will depend on how big of a mess the expressions are. For your example above, the following works for me:

X=X.subs(a==S1+b)
X=X.subs(d == S2*1/S1*(1+S1)).simplify()


As you wanted, this produces S2^2 + S1 + S2 + e^S2. Unfortunately, this approach still leaves you to manually determine what S1 and S2 should be, which is not what you wanted. I'm not sure how to automate this completely as you suggest.

more

Thank you, but unfortunately, the automatisation (or more specifically the automatic detection of possible substitutions) is what I really need.