Search code examples
python-3.xsympysymbolic-math

Converting an equation to another form using sympy


I have such a problem: I have an expression like x ** 3 - x ** 2 + x - 5 = 0. I need to convert it to the form x = g(x), such as x = root(x ** 2 - x + 5, 3).

Can sympy do this? If so, how? Thank you for your informative answer.


Solution

  • You can replace the x**3 term with y**3 and solve for y:

    In [26]: lhs = x ** 3 - x ** 2 + x - 5                                                                                                         
    
    In [27]: lhs                                                                                                                                   
    Out[27]: 
     3    2        
    x  - x  + x - 5
    
    In [28]: lhs.subs(x**3, y**3)                                                                                                                  
    Out[28]: 
       2        3    
    - x  + x + y  - 5
    
    In [29]: y1, y2, y3 = solve(lhs.subs(x**3, y**3), y)                                                                                           
    
    In [30]: Eq(x, y3)                                                                                                                             
    Out[30]: 
           ____________
        3 ╱  2         
    x = ╲╱  x  - x + 5