Search code examples
pythonnumpylambdapiecewise

Python — confused by numpy's piecewise function


I'm trying to implement a piecewise function in Python. Since I'm using quite a few tools from numpy, I simply import everything from it (i.e. from numpy import *). My piecewise function is defined as

LinQuad = piecewise( t, [t < 1, t >= 1], [lambda t : t, lambda t : t**2] )

which results in the error NameError: global name 't' is not defined. I don't understand why I should define t — after all, it is not necessary to define t for a simple lambda function Lin = lambda t : t. In some examples the domain of t is defined, but I don't know at which values the function LinQuad will be evaluated. What to do?


Solution

  • I'm no numpy expert, but it looks to me like you're expecting piecewise to return a function that you can then use elsewhere. That's not what it does - it calculates the function result itself. You could probably write a lambda expression that would take an arbitrary domain and return your calculation on it:

    LinQuad = lambda x: piecewise(x, [x < 1, x >= 1], [lambda t: t, lambda t: t**2])
    

    I am none too sure about defining the condlist boolean arrays there - presumably that's something specific to numpy.

    Or if appropriate to your situation:

    def LinQuad(x):
       return piecewise(x, [x < 1, x >= 1], [lambda t: t, lambda t: t**2])