Executing the below code in Sympy 1.11.1 returns NaN
.
from sympy import *
x = Symbol("x", real=True)
p = Piecewise((0, x < 0), (0, x > 0), (1, x == 0))
p.subs(x,0)
>>>> nan
I expected the result to be 1
. What is happening here, and is there a workaround?
Print out your expressions to see the problem:
In [1]: from sympy import *
...: x = Symbol("x", real=True)
...: p = Piecewise((0, x < 0), (0, x > 0), (1, x == 0))
...: p.subs(x,0)
Out[1]: nan
In [2]: p
Out[2]: {0 for x > 0 ∨ x < 0
In [3]: x == 0
Out[3]: False
In [4]: Eq(x, 0)
Out[4]: x = 0
In [5]: p2 = Piecewise((0, x < 0), (0, x > 0), (1, Eq(x, 0)))
In [6]: p2
Out[6]:
⎧0 for x > 0 ∨ x < 0
⎨
⎩1 for x = 0
In [7]: p2.subs(x, 0)
Out[7]: 1
The problem is that x == 0
in sympy is for structural equality i.e. it is for checking whether two expressions are syntactically identical. To create a symbolic boolean expressing the symbolic condition that x
is equal to zero you need to use Eq(x, 0)
.