Defining a complex-valued, piecewise function
Question: I'm trying to define a function f(x) which yields 1.0 for x = 0 and 1.0/(2j pi
x) otherwise. Here is a 'test' script I'm using:

    
    
    import numpy as np
    
    def f(x):
        return np.piecewise(x,[x==0],[1.0, lambda x: 1.0/(2j*np.pi*x)])
    
    x = np.linspace(-1,1,21)
    
    print(x)
    print(f(x))
    

If the lambda function is not complex-valued, this works as I would expect.
However, with the "2j" term I get the following warning and output:

    
    
    /usr/local/lib/python2.7/dist-packages/numpy/lib/function_base.py:1144: ComplexWarning: Casting complex values to real discards the imaginary part
      y[condlist[k]] = item(vals, *args, **kw)
    [-1.  -0.9 -0.8 -0.7 -0.6 -0.5 -0.4 -0.3 -0.2 -0.1  0.   0.1  0.2  0.3  0.4
      0.5  0.6  0.7  0.8  0.9  1. ]
    [-0. -0. -0. -0. -0. -0. -0. -0. -0. -0.  1.  0.  0.  0.  0.  0.  0.  0.
      0.  0.  0.]
    

Apparently numpy's `piecewise` automatically takes the real part. Is this not
quite a limitation of `piecewise`? Is there another way to define piecewise
complex-valued functions (without having to define the real and imaginary
parts separately)?


Answer: From the
[`piecewise`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.piecewise.html)
docstring:

    
    
    The output is the same shape and type as x...
    

For complex output, pass in a complex array.

Continuing your example with `f` and `x` defined:

    
    
    In [91]: y = x + 0j
    
    In [92]: f(y)
    Out[92]: 
    array([-0.+0.15915494j, -0.+0.17683883j, -0.+0.19894368j, -0.+0.2273642j ,
           -0.+0.26525824j, -0.+0.31830989j, -0.+0.39788736j, -0.+0.53051648j,
           -0.+0.79577472j, -0.+1.59154943j,  1.+0.j        ,  0.-1.59154943j,
            0.-0.79577472j,  0.-0.53051648j,  0.-0.39788736j,  0.-0.31830989j,
            0.-0.26525824j,  0.-0.2273642j ,  0.-0.19894368j,  0.-0.17683883j,
            0.-0.15915494j])
    

