Search code examples
sympyfloorpiecewise

Sympy Piecewise expression for even and odd numbers


The objective is to implement a Piecewise expression that gives 0 when n is even, and 1 when n is odd. One way to do it is using the floor function like below:

from sympy import *
from sympy.abc import n

f = Lambda((n,), Piecewise((0, Eq(n, floor(n / S(2)))),
                           (1, Eq(n, floor(n / S(2))+1))))

print(f(0))
print(f(1))
print(f(2))
print(f(3))

However, this returns the wrong output:

0
1
1
Piecewise()

The correct output should be:

0
1
0
1

Another way to achieve the same is to use:

from sympy import *
from sympy.abc import n

f = Lambda((n,), Piecewise((0, Eq((-1)**n, 1)),
                           (1, Eq((-1)**n, -1))))

print(f(0))
print(f(1))
print(f(2))
print(f(3))

and this returns the correct output. Is there a way to achieve this using the floor function in the original code?


Solution

  • A better way would be to use Mod, like

    Piecewise((0, Eq(Mod(n, 2), 0)), (1, Eq(Mod(n, 2), 1)))
    

    However, since your function coincides exactly with the definition of Mod, you can just use it directly

    Mod(n, 2)
    

    or equivalently

    n % 2