我有以下函式,但是當我運行程式時,我只有“大小為 1 的陣列可以轉換為 Python 標量”的錯誤
import math as math
import numpy as np
def chebs(c, d, n):
k = np.array(range(n))
y = ((2*k 1)*np.pi)/(4*(n 1))
return c*math.sin(y)**2 d*math.cos(y)**2
有沒有辦法規避錯誤?我假設它來自我在函式中使用數學?
uj5u.com熱心網友回復:
您不能numpy.與math.函式混合使用,只能使用numpy.函式:
import numpy as np
def chebs(c, d, n):
k = np.arange(n)
y = ((2 * k 1) * np.pi) / (4 * (n 1))
return c * np.sin(y) ** 2 d * np.cos(y) ** 2
uj5u.com熱心網友回復:
中的函式math通常需要一個數字作為引數;而 innumpy中的函式通常期望從單個數字到多維陣列的任何內容,并將數學函式應用于陣列中的每個元素。
例如:
>>> import math
>>> import numpy as np
>>> math.sqrt(4)
2.0
>>> math.sqrt(25)
5.0
>>> np.sqrt(4)
2.0
>>> np.sqrt(25)
5.0
>>> np.sqrt([4,25])
array([2., 5.])
>>> math.sqrt([4,25])
TypeError: must be real number, not list
>>> math.sqrt(np.array([4,25]))
TypeError: only size-1 arrays can be converted to Python scalars
事實證明,包含單個數字的 numpy 陣列能夠在需要時將自己隱式轉換為沒有陣列的單個數字,因此這是有效的:
>>> math.sqrt(np.array([[25]]))
5.0
您收到的錯誤訊息告訴您“陣列y包含多個數字,因此無法將其轉換為單個數字,因此您無法呼叫math.sin它。”
如果要將函式 frommath應用于串列中的每個元素,可以使用串列理解或使用內置函式來實作map。但是,請注意,整個重點numpy是在大型陣列上非常快速地執行計算,并且使用串列推導式或map將破壞該目的。
>>> list(map(math.sqrt, [4, 25]))
[2.0, 5.0]
>>> [math.sqrt(x) for x in [4,25]]
[2.0, 5.0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341064.html
