NumPy power() 函数用于按元素计算第二个数组的第一个数组元素的幂。
语法
numpy.power(x, y, out=None)
参数
x | 必填。 指定第一个包含元素的数组作为基础。 |
y | 必需。 指定包含指数元素的第二个数组。如果 x.shape != y.shape,它们必须可广播为通用形状(成为输出的形状)。 |
out | 可选。 指定存储结果的位置。如果提供,它必须具有输入广播到的形状。如果未提供或无,则返回新分配的数组。 |
返回值
返回x中的底数到y中的指数
示例:指数作为标量
在下面的示例中,numpy power() 函数用于计算每个元素的平方和立方。
import numpy as np
Arr = np.array([1, 2, 3, 4, 5])
print("The square of values:")
print(np.power(Arr, 2))
print("\nThe cube of values:")
print(np.power(Arr, 3))
上述代码的输出将是:
The square of values:
[ 1 4 9 16 25]
The cube of values:
[ 1 8 27 64 125]
示例:指数为数组
此示例演示如何使用指数作为数组。
import numpy as np
base = np.array([5, 6, 7])
exponent = np.array([0, 1, 2])
print("The power of values:")
print(np.power(base, exponent))
上述代码的输出将是:
The power of values:
[ 1 6 49]