1

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

Athul Dev
  • 61
  • 5
  • 1
    It's not easy to translate `if` expressions like that into working `numpy` code. By itself an `if` does not iterate over the elements of an array, and using an array inside an `if` results in an `ambiguity` ValueError. Do you really need `lambdify` for this? Can't you stick with `sympy`, or do the calculation directly in `numpy`? – hpaulj Jun 15 '20 at 16:24
  • hpaulj , yeah , unfortunately I need to pack this code as a function, to be able to apply it to different set of numbers. – Athul Dev Jun 16 '20 at 04:36
  • You can write a Python/numpy function that does this without going through `sympy`. – hpaulj Jun 16 '20 at 05:07
  • Can you elaborate? – Athul Dev Jun 16 '20 at 05:10

1 Answers1

3

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

Oscar Benjamin
  • 12,649
  • 1
  • 12
  • 14
  • 1
    `y.__doc__` shows that resulting `numpy` code is `select([equal(mod(ceil(x), 2), 0),True], [1,-1], default=nan)` – hpaulj Jun 16 '20 at 05:05