分段函数的积分

0 投票
1 回答
840 浏览
提问于 2025-04-18 00:36

我正在尝试对两个分段函数的乘积在区间(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

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

可以试试这样做:

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 的函数也可能需要这样重新定义。

撰写回答