I'm using sympy for automatic code generation and differentiation. Before code generation I perform common subexpression simplification. I'm getting weird results in one of my expressions, though. I get a substitution for (_cse1, x0**3) and then in my expression I get _cse1**(2/3) instead of x0**2. Although both expressions are mathematically equivalent, numerically x0**2 is much more efficient and robust. Bellow is a code snippet of this particular expression.
>>> import sympy
>>> variables = sympy.var('x:10 hyperpar:10 u:10 u_dot:10 dt theta:10')
>>> e = 0.5*dt**2*hyperpar9**2*x1 + 0.5*dt**2*hyperpar9*theta0*x0**3 + 0.5*dt**2*hyperpar9*theta1*x0 - 0.5*dt**2*hyperpar9*u0 - 1.5*dt**2*theta0*x0**2*x1 - 0.5*dt**2*theta1*x1 + 0.5*dt**2*u_dot0 - dt*hyperpar9*x1 - dt*theta0*x0**3 - dt*theta1*x0 + dt*u0 + x1
>>> sympy.cse(e, sympy.numbered_symbols('_cse'))
([(_cse0, dt**2), (_cse1, x0**3), (_cse2, theta1*x0), (_cse3, 0.5*_cse0), (_cse4, _cse1*theta0)], [-1.5*_cse0*_cse1**(2/3)*theta0*x1 + _cse2*_cse3*hyperpar9 - _cse2*dt + _cse3*_cse4*hyperpar9 + _cse3*hyperpar9**2*x1 - _cse3*hyperpar9*u0 - _cse3*theta1*x1 + _cse3*u_dot0 - _cse4*dt - dt*hyperpar9*x1 + dt*u0 + x1])