我正在運行這個程式:
def f2d(x,y):
# condition
if 4*x**2 y**2 <= 4:
return np.sin(x*y)
else:
return 0
def my_prog(function,n):
x = np.random.uniform(low=-1, high= 1, size=(n))
y = np.random.uniform(low=-2, high= 2, size=(n))
f = function(x,y)
return (f,n)
(f,n) = my_prog(f2d,5)
我得到這個錯誤:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
這不是很清楚:我不明白如何插入a.any()或a.all()在我制作的程式中,我應該在哪里做,為什么......
我的目標只是f創建一個一維陣列(就像一x維y陣列一樣)并包含np.sin(x*y)條件是否滿足,或者0條件不滿足,如def f2d(x,y)? 因此,它看起來像是一種在特定條件下對陣列x進行元素明智的操作。y但我不明白為什么它不起作用。我應該先創建f一個空陣列嗎?問題是從那里來的嗎?
uj5u.com熱心網友回復:
if-clause 期望一個真值,但4*x**2 y**2 <= 4它是形狀 (5,) 布爾陣列。要讓它作業,您應該將其轉換為單個真值或迭代它,具體取決于您要執行的操作。但是,出于您的任務的目的,您可以numpy.where根據條件使用來選擇值。在這種情況下,np.sin(x*y)如果滿足條件,則選擇 from,否則選擇 0。
def f2d(x,y):
# condition
return np.where(4*x**2 y**2 <= 4, np.sin(x*y), 0)
測驗運行:
>>> my_prog(f2d,5)
(array([0.02896101, 0.34900898, 0. , 0. , 0.15721751]), 5)
uj5u.com熱心網友回復:
問題出在 下# condition,將運算結果與 4 比較后,會得到一個布爾陣列,但是這個布爾陣列不能轉換為真值,所以會報錯,像這樣:
>>> np.arange(8) < 5
array([ True, True, True, True, True, False, False, False])
>>> if np.arange(8) < 5:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/468191.html
下一篇:數值查找非均勻二維資料的一階導數
