📜  按元素获取 NumPy 数组值的幂

📅  最后修改于: 2022-05-13 01:55:00.571000             🧑  作者: Mango

按元素获取 NumPy 数组值的幂

NumPy 是一个强大的 N 维数组对象,它用于线性代数、傅里叶变换和随机数功能。它提供的数组对象比传统的Python列表快得多。 numpy.power() 用于计算元素的幂。它按元素处理从第二个数组提升到幂的第一个数组元素。

因此,让我们讨论一些与获取数组功能相关的示例。

示例 1:计算具有不同元素值的数组的幂。

Python3
# import required modules
import numpy as np
 
 
# creating the array
sample_array1 = np.arange(5)
sample_array2 = np.arange(0, 10, 2)
 
print("Original array ")
print("array1 ", sample_array1)
print("array2 ", sample_array2)
 
# calculating element-wise power
power_array = np.power(sample_array1, sample_array2)
 
print("power to the array1 and array 2 : ", power_array)


Python3
# import required module
import numpy as np
 
 
# creating the array
array = np.arange(8)
print("Original array")
print(array)
 
# computing the power of array
print("power of 3 for every element-wise:")
print(np.power(array, 3))


Python3
# import required modules
import numpy as np
 
 
# creating the array
sample_array1 = np.arange(5)
 
# initialization the decimal number
sample_array2 = [1.0, 2.0, 3.0, 3.0, 2.0]
 
print("Original array ")
print("array1 ", sample_array1)
print("array2 ", sample_array2)
 
# calculating element-wise power
power_array = np.power(sample_array1, sample_array2)
 
print("power to the array1 and array 2 : ", power_array)


Python3
# importing module
import numpy as np
 
 
# creating the array
array = np.arange(8)
print("Original array")
print(array)
print("power of 3 for every element-wise:")
 
# computing the negative power element
print(np.power(array, -3))


输出:

Original array 
array1  [0 1 2 3 4]
array2  [0 2 4 6 8]
power to the array1 and array 2 :  [    1     1    16   729 65536]

示例 2:为数组中的每个元素计算相同的幂。

Python3

# import required module
import numpy as np
 
 
# creating the array
array = np.arange(8)
print("Original array")
print(array)
 
# computing the power of array
print("power of 3 for every element-wise:")
print(np.power(array, 3))

输出:

Original array
[0 1 2 3 4 5 6 7]
power of 3 for every element-wise:
[  0   1   8  27  64 125 216 343]

示例 3:计算十进制值的幂。

Python3

# import required modules
import numpy as np
 
 
# creating the array
sample_array1 = np.arange(5)
 
# initialization the decimal number
sample_array2 = [1.0, 2.0, 3.0, 3.0, 2.0]
 
print("Original array ")
print("array1 ", sample_array1)
print("array2 ", sample_array2)
 
# calculating element-wise power
power_array = np.power(sample_array1, sample_array2)
 
print("power to the array1 and array 2 : ", power_array)

输出:

Original array 
array1  [0 1 2 3 4]
array2  [1.0, 2.0, 3.0, 3.0, 2.0]
power to the array1 and array 2 :  [ 0.  1.  8. 27. 16.]

注意:你不能计算负功率

示例 4:

Python3

# importing module
import numpy as np
 
 
# creating the array
array = np.arange(8)
print("Original array")
print(array)
print("power of 3 for every element-wise:")
 
# computing the negative power element
print(np.power(array, -3))

输出: