![](/img/trans.png)
[英]Python: Piecewise function integration error: "TypeError: cannot determine truth value of ..."
[英]Integration of a piecewise function
我正在嘗試在(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()。 有人可以幫我修復錯誤嗎? 非常感謝你。
問題可能出在分段函數的定義中。
嘗試通過這種方式:
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
對於邏輯向量數組,使用&
代替and
對於邏輯向量數組,請注意使用np.where
作為向量化if-else替代。
我沒有嘗試修復整個代碼,需要if-else的其他函數也可能需要重新定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.