定义复值的分段函数

时间:2016-06-30 17:28:18

标签: python numpy

我试图定义一个函数f(x),否则x = 0和1.0 /(2j pi x)会产生1.0。这是一个'测试'脚本我正在使用:

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))

如果lambda函数不是复值的,那就像我期望的那样工作。但是,使用" 2j"术语我得到以下警告和输出:

/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.]

显然numpy的piecewise会自动占据真实的一部分。这不是piecewise的限制吗?是否有另一种方法来定义分段复值函数(无需单独定义实部和虚部)?

1 个答案:

答案 0 :(得分:1)

来自piecewise docstring:

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

对于复杂输出,传入复杂数组。

继续您的示例fx已定义:

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])