Sympy Piecewise expression for even and odd numbers

59 views
Skip to first unread message

Dzhelil Rufat

unread,
Oct 22, 2015, 4:20:13 PM10/22/15
to sympy
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?

PS: Question also posted on http://stackoverflow.com/questions/33289928/sympy-piecewise-expression-for-even-and-odd-numbers

Aaron Meurer

unread,
Oct 22, 2015, 5:47:06 PM10/22/15
to sy...@googlegroups.com
I answered on StackOverflow. The short answer is, use Mod.

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups
> "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sympy.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/sympy/038eb56e-4bae-4fce-ac7b-5006e4607404%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages