Search code examples
pythonpython-3.xsympysymbolic-math

How to remove a Coefficient of (1) from SymPy symbolic expression?


I want to remove any coefficient that is equal to 1 in sympy symbolic expression , for example: I want 1.0x**2 to be x**2 , Is there anyway to do it ? Also if possible to round integers , for example 2.0x**2 to be 2*x**2


Solution

  • You can use nsimplify:

    In [4]: nsimplify(2.0*x**2)
    Out[4]: 
       2
    2⋅x 
    

    in a Python shell

    >>> import sympy
    >>> sympy.nsimplify("1.0*x**2")
    x**2
    >>> sympy.nsimplify("2.0*x**2")
    2*x**2