使用 NumPy 对数组的元素进行指定值的幂运算,并在不同的数据类型中显示结果
要对数组的元素进行指定值的幂运算,可以使用 Python 中的 **numpy.power()** 方法。这里,第一个参数是底数,第二个参数是指数。**dtype** 参数用于设置输出数据类型。
将 x1 中的每个底数都提升到 x2 中位置对应的幂。x1 和 x2 必须能够广播到相同的形状。整数类型提升到负整数幂将引发 ValueError。负值提升到非整数值将返回 nan。要获得复数结果,请将输入转换为复数,或将 dtype 指定为复数。
此条件将广播到输入上。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他位置,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化状态。
步骤
首先,导入所需的库:
import numpy as np
创建一个数组:
arr = np.array([5, 10, 25, 30, 40, 50])
显示数组:
print("Array...
", arr)获取数组的类型:
print("
Our Array type...
", arr.dtype)
获取数组的维度:
print("
Our Array Dimension...
",arr.ndim)获取数组的形状:
print("
Our Array Shape...
",arr.shape)
设置指数:
p = 2.5
要对数组的元素进行指定值的幂运算,可以使用 Python 中的 numpy.power() 方法。这里,第一个参数是底数,第二个参数是指数。dtype 参数用于设置输出数据类型:
print("
Result...
",np.power(arr, p, dtype = complex))
示例
import numpy as np
# Create an array
arr = np.array([5, 10, 25, 30, 40, 50])
# Display the array
print("Array...
", arr)
# Get the type of the array
print("
Our Array type...
", arr.dtype)
# Get the dimensions of the Array
print("
Our Array Dimension...
",arr.ndim)
# Get the shape of the Array
print("
Our Array Shape...
",arr.shape)
# Set the exponent
p = 2.5
# To power array elements of an array with a given value, use the numpy.power() method in Python
# Here, the 1st parameter is the base and the 2nd exponents
# The dtype parameter is used to set the output datatype
print("
Result...
",np.power(arr, p, dtype = complex))输出
Array... [ 5 10 25 30 40 50] Our Array type... int64 Our Array Dimension... 1 Our Array Shape... (6,) Result... [ 55.90169944+0.j 316.22776602+0.j 3125. +0.j 4929.50301755+0.j 10119.28851254+0.j 17677.66952966+0.j]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP