numpy.power#

numpy.power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature]) = <ufunc 'power'>#

將第一個陣列元素提升為來自第二個陣列的冪,逐元素運算。

x1 中的每個底數提升為 x2 中位置對應的冪。x1x2 必須可廣播為相同的形狀。

整數類型提升為負整數冪將引發 ValueError

負值提升為非整數值將返回 nan。若要取得複數結果,請將輸入轉換為複數,或指定 dtypecomplex (請參閱以下範例)。

參數:
x1array_like

底數。

x2array_like

指數。如果 x1.shape != x2.shape,它們必須可廣播為共同的形狀 (這會變成輸出的形狀)。

outndarray, None 或 ndarray 和 None 的 tuple, 選用

結果儲存的位置。如果提供,則必須具有輸入可廣播至的形狀。如果未提供或為 None,則會返回新配置的陣列。tuple (僅能作為關鍵字引數) 的長度必須等於輸出的數量。

wherearray_like, 選用

此條件會廣播到輸入上。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他位置,out 陣列將保留其原始值。請注意,如果透過預設 out=None 建立未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化。

**kwargs

對於其他僅限關鍵字的引數,請參閱 ufunc 文件

返回:
yndarray

x1 中的底數提升為 x2 中的指數。如果 x1x2 都是純量,則這是一個純量。

另請參閱

float_power

將整數提升為浮點數的 power 函式

範例

>>> import numpy as np

計算陣列中每個元素的立方。

>>> x1 = np.arange(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([  0,   1,   8,  27,  64, 125])

將底數提升為不同的指數。

>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])

廣播的效果。

>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
       [1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0,  1,  8, 27, 16,  5],
       [ 0,  1,  8, 27, 16,  5]])

** 運算子可以用作 ndarray 上 np.power 的簡寫。

>>> x2 = np.array([1, 2, 3, 3, 2, 1])
>>> x1 = np.arange(6)
>>> x1 ** x2
array([ 0,  1,  8, 27, 16,  5])

負值提升為非整數值將導致 nan (並且會產生警告)。

>>> x3 = np.array([-1.0, -4.0])
>>> with np.errstate(invalid='ignore'):
...     p = np.power(x3, 1.5)
...
>>> p
array([nan, nan])

若要取得複數結果,請提供引數 dtype=complex

>>> np.power(x3, 1.5, dtype=complex)
array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])