當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python numpy.power()用法及代碼示例


numpy.power(arr1,arr2,out = None,where = True,cast ='same_kind',order ='K',dtype = None):
來自第一個數組的數組元素被提升為來自第二個元素的元素的冪(所有情況都逐個元素發生)。 arr1和arr2必須具有相同的形狀,並且arr1中的每個元素都必須從arr2升高到相應的+ ve值;否則將引發ValueError。
參數:

arr1     : [array_like]Input array or object which works as base.
arr2     : [array_like]Input array or object which works as exponent. 
out      : [ndarray, optional]Output array with same dimensions as Input array, 
           placed with result.
**kwargs : Allows you to pass keyword variable length of argument to a function. 
           It is used when we want to handle named argument in a function.
where    : [array_like, optional]True value means to calculate the universal 
           functions(ufunc) at that position, False value means to leave the 
           value in the output alone.

返回:

An array with elements of arr1 raised to exponents in arr2


代碼1:將arr1提升為arr2


# Python program explaining 
# power() function 
import numpy as np 
  
# input_array 
arr1 = [2, 2, 2, 2, 2] 
arr2 = [2, 3, 4, 5, 6] 
print ("arr1         : ", arr1) 
print ("arr1         : ", arr2) 
  
# output_array 
out = np.power(arr1, arr2) 
print ("\nOutput array : ", out)

輸出:

arr1         :  [2, 2, 2, 2, 2]
arr2         :  [2, 3, 4, 5, 6]

Output array :  [ 4  8 16 32 64]


代碼2:將arr1的元素提高到指數2

# Python program explaining 
# power() function 
import numpy as np 
  
# input_array 
arr1 = np.arange(8) 
exponent = 2
print ("arr1         : ", arr1) 
  
# output_array 
out = np.power(arr1, exponent) 
print ("\nOutput array : ", out)

輸出:

arr1         :  [0 1 2 3 4 5 6 7]

Output array :  [ 0  1  4  9 16 25 36 49]


代碼3:如果arr2具有-ve元素,則錯誤

# Python program explaining 
# power() function 
import numpy as np 
  
# input_array 
arr1 = [2, 2, 2, 2, 2] 
arr2 = [2, -3, 4, -5, 6] 
print ("arr1         : ", arr1) 
print ("arr2         : ", arr2) 
  
# output_array 
out = np.power(arr1, arr2) 
print ("\nOutput array : ", out)

輸出:

arr1         :  [2, 2, 2, 2, 2]
arr2         :  [2, -3, 4, -5, 6]
ValueError: Integers to negative integer powers are not allowed.

參考文獻:
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.power.html#numpy.power



相關用法


注:本文由純淨天空篩選整理自Mohit Gupta_OMG 大神的英文原創作品 numpy.power() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。