整合分段函数

时间:2014-03-30 23:00:02

标签: python numpy

我试图在(0,1)上集成两个分段函数的乘积。我的代码如下:

def gfunc1(x):
    if np.logical_and(x >= 0.5, x<=1):
        temp =(-1.0)*np.pi*np.cos(np.pi*x)+(x+0.5)*(np.pi**2)*np.sin(np.pi*x)
    else:
        temp = np.pi*np.cos(np.pi*x)+(1.5-x)*(np.pi**2)*np.sin(np.pi*x)
    return temp
def lfunc(x,*args):
    return args[0](x)*args[1](x,args[2])
def bfunc(x,i):
    if (i == 0):
        if np.logical_and(x <= dxl[1], x>= dxl[0]):
            temp = (dxl[1] - x)/(dxl[1]-dxl[0])
        else:
            temp = 0.0
    elif (i == (len(dxl)-1)):
        if np.logical_and(x >= dxl[len(dxl)-2], x <= dxl[len(dxl)-1]):
            temp = (x- dxl[len(dxl)-2])/(dxl[len(dxl)-1] - dxl[len(dxl)-2])
        else:
            temp = 0.0
    else:
        if np.logical_and(dxl[i-1]<=x,x<=dxl[i]):
            temp = (x - dxl[i-1])/(dxl[i]-dxl[i-1])
        elif np.logical_and(dxl[i]<=x,x<=dxl[i+1]):
            temp =(dxl[i+1]-x)/(dxl[i+1]-dxl[i])
        else:
            temp = 0.0
    return temp
dxl = np.linspace(0,1,100)
res = quadrature(lfunc,0,1,args=(gfunc1,bfunc,1))
print res[0]

我收到错误消息:ValueError:具有多个元素的数组的真值是不明确的。使用a.any()或a.all()。 有人可以帮我解决这个问题吗?非常感谢你。

1 个答案:

答案 0 :(得分:0)

问题可能在于分段函数的定义。

尝试这样做:

def gfunc1(x):
    return np.where( ((x >= 0.5) & (x<=1)), 
        (-1.0)*np.pi*np.cos(np.pi*x)+(x+0.5)*(np.pi**2)*np.sin(np.pi*x),
         np.pi*np.cos(np.pi*x)+(1.5-x)*(np.pi**2)*np.sin(np.pi*x)  )

请注意,对于逻辑矢量数组,使用&代替and, 以及使用np.where作为矢量化if-else替代。

我没有尝试修复整个代码,其他需要if-else的函数也可能需要以这种方式重新定义。

相关问题