Search code examples
pythonvectorsympy

Constant simplification in Sympy


I had a trouble in Python when working with Sympy.

When I do some stuff and I got this vector:

result
>>>[0 + 1, -0 - 3*a/2 - 1/2, a]

How can I simplify that vector to this:

[1, - 3*a/2 - 1/2, a]

I had tried almost all method like simplify, collection,... in Sympy documentation but it does not work. Please help me to treat this case. Thanks!


Solution

  • Symbols can have any name -- even '0' -- and this can be useful if you want to track the algebra involving that symbol to see, for example, that it never ends up in the denominator. But If you didn't intend for that, use S.Zero instead of Symbol("0"). Or replace that symbol with a value at the end:

    >>> from sympy.abc import a
    >>> from sympy import Tuple, Symbol
    >>> z = Symbol("0")
    >>> v = [z + 1, -z - 3*a/2 - S.Half, a]; v
    [0 + 1, -0 - 3*a/2 - 1/2, a]
    >>> [i.subs(z, 0) for i in v]
    [1, -3*a/2 - 1/2, a]
    >>> [i.subs('0', 0) for i in v] == _
    True
    

    I am surprised that the last substitution (as suggested by Remmelzwaal) works.