0

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!

  • 1
    `simplify` seems to work fine for me. Could you post the rest of your code? – B Remmelzwaal Mar 29 '23 at 12:10
  • [code](https://ideone.com/RuS8u6): My code is very complex, so you just read function `back_substitution` begin from line 81 – Queensalats Mar 29 '23 at 13:13
  • I think the issue lies in the line `zero = symbols('0')`. Now, (-)0 are treated the same as any other variable, like `x, y, z`, so they cannot be simplified away by evaluating it as a literal 0. Why aren't you just doing `y.append(0)`? Or `expr = expr.subs('0', 0)`? – B Remmelzwaal Mar 29 '23 at 13:36
  • 1
    `y.append(0)` is work. I thought that type List in Python just hold elements which have the same type. I forgot `sympy` can work perfectly with numeric type and symbols. Thank you so much. – Queensalats Mar 29 '23 at 15:28

1 Answers1

0

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.

smichr
  • 16,948
  • 2
  • 27
  • 34