Search code examples
sympylambdify

Lambdifying a function with conditon statements using sympy


Im trying to lambdify this function

def f(x):
    if ceil(x)%2 == 0:
        return -1
    else :
        return +1
a = sympy.lambdify(x,f(x))

Im getting an error when i try to do that. I also tried piecewise , but it is not giving me the desired outcome

y = lambdify(x,(Piecewise((1, ceil(x)%2 == 0), (-1,True))))

Please help Thanks in advance


Solution

  • You need to pass a symbolic expression to lambdify so a Python function is no good. Also you need to use symbolic sympy functions and sympy's ceil function is actually called ceiling. Finally == compares if two expressions are the same which is not the same as constructing a symbolic Boolean. For that you need Eq: That gives

    In [19]: p = Piecewise((1, Eq(ceiling(x)%2, 0)), (-1,True))
    
    In [20]: p
    Out[20]: 
    ⎧1   for ⌈x⌉ mod 2 = 0
    ⎨                     
    ⎩-1      otherwise    
    
    In [21]: y = lambdify(x, p)
    
    In [22]: y([1, 2, 3])
    Out[22]: array([-1.,  1., -1.])
    

    References:

    https://docs.sympy.org/latest/modules/functions/elementary.html#ceiling https://docs.sympy.org/latest/tutorial/gotchas.html#equals-signs