NumPy power()

power() 函数用于将数组的元素提高到指定的幂。

示例

import numpy as np

# create an array for the base values
base = np.array([2, 3, 4])

# create an array for the exponent values
exponent = np.array([2, 3, 4])

# use power() to raise the base values to the power of the corresponding exponent values result = np.power(base, exponent)
print(result) # Output : [ 4 27 256]

power() 语法

power() 的语法是

numpy.power(base, exponent, out=None)

power() 参数

power() 函数接受一个参数

  • base - 包含基数的输入数组
  • exponent - 指数的值或数组,它可以是标量或与 base 形状相同的数组。
  • out (可选) - 用于存储结果的输出数组

power() 返回值

power() 函数返回一个数组,其中包含 base 数组的元素提高到 exponent 数组中相应元素的幂。


示例 1:带标量指数的 power()

import numpy as np

# create an array for the base values
base = np.array([1, 2, 3, 4, 5])

# specify the exponent value
exponent = 3

# use power() to raise the base values to the specified exponent result = np.power(base, exponent)
print(result)

输出

[  1   8  27  64 125]

在此示例中,我们使用 power() 函数将 base 数组中的每个元素提高到指定 exponent 的幂。


示例 2:带指数值数组的 power()

import numpy as np

# create an array for the base values
base = np.array([2, 3, 4])

# create an array for the exponent values
exponent = np.array([4, 2, 1])

# use power() to raise the base values to the power of the corresponding exponent values result = np.power(base, exponent)
print(result)

输出

[16  9  4]

示例 3:在 power() 中使用 out 参数

import numpy as np

base = np.array([7, 8, 9, 10, 12])
exponent = 2

# create an empty array with the same shape as the base array
result = np.zeros_like(base)
# calculate the power and store the result in the out_array np.power(base, exponent, out=result)
print(out_array)

输出

[ 49  64  81 100 144]

在此,在指定 out=result 后,幂运算的结果存储在 result 数组中。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战