NumPy 计算数组中所有元素的倒数

NumPy 计算数组中所有元素的倒数

倒数是指一个数的乘法逆元,当我们有一个非零数’a’时,它的倒数将是’b’,即a * b = 1。换句话说,’a’的倒数表示为’1/a’。

reciprocal()函数

我们可以使用Numpy库的reciprocal()函数计算数组的倒数。该函数接受一个数组作为参数,并返回给定数组元素的倒数,大小和形状与原始数组相同。

语法

以下是将reciprocal()函数应用于数组的语法。

numpy.reciprocal(x, out=None)

其中,

  • x是输入数组。

  • out是可选参数,代表存储结果数组的位置。它必须与输入数组具有相同的形状。如果不提供此值,则创建一个新数组并将结果值存储在其中。

示例

在下面的示例中,为了计算给定输入数组的倒数,我们将数组作为参数传递给 reciprocal() 函数。

import numpy as np
a = np.array([34,23,90,34,100])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
reci = np.reciprocal(a,dtype = float)
print("The reciprocal of the given 1-d array:",reci)

输出

The input array: [ 34 23 90 34 100]
The dimension of the array: 1
The reciprocal of the given 1-d array: [0.02941176 0.04347826 0.01111111 0.02941176 0.01 ]

示例

在下面的示例中,我们将不提及数据类型,所以输出数组的默认数据类型将是整数,不会返回浮点数值。

import numpy as np
a = np.array([34,23,90,34,100])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
reci = np.reciprocal(a)
print("The reciprocal of the given 1-d array:",reci)

输出

The input array: [ 34 23 90 34 100]
The dimension of the array: 1
The reciprocal of the given 1-d array: [0 0 0 0 0]

示例

这是另一个示例,使用倒数函数计算二维数组元素的倒数。

import numpy as np
a = np.array([[34,23],[90,34]])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
reci = np.reciprocal(a,dtype = float)
print("The reciprocal of the given 2-d array:",reci)

输出

The input array: [[34 23]
[90 34]]
The dimension of the array: 2
The reciprocal of the given 2-d array: [[0.02941176 0.04347826]
[0.01111111 0.02941176]]

注意

reverse()函数输出的数组元素默认属于int数据类型,因此在某些情况下,我们只会看到输出为零。如果我们希望将整个浮点数作为输出显示,则必须在reverse()函数中使用float数据类型来定义数组输入。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程