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

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

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

在本文中,让我们讨论如何计算给定 NumPy 数组的所有元素的倒数。

方法一:通过reciprocal_arr = 1/arr语句,我们可以将arr的每一个元素都转换成倒数,并保存到reciprocal_arr中。但是有个catch,如果“arr”的任何一个元素为0,就会报错。所以请注意不要将任何数组传递给包含 0 的 reciprocal_arr。

示例 1:

Python
# PROGRAM TO FIND RECIPROCAL OF EACH 
# ELEMENT OF NUMPY ARRAY
import numpy as np
  
lst = [22, 34, 65, 50, 7]
arr = np.array(lst)
reciprocal_arr = 1/arr
  
print(reciprocal_arr)


Python
# PROGRAM TO FIND RECIPROCAL OF EACH
# ELEMENT OF NUMPY ARRAY
import numpy as np
  
tup = (12, 87, 77, 90, 57, 34)
arr = np.array(tup)
reciprocal_arr = 1/arr
  
print(reciprocal_arr)


Python3
#  program to compute the Reciprocal
# for all elements in a given array
# with the help of numpy.reciprocal()
import numpy as np
  
arr = [2, 1.5, 8, 9, 0.2]
reciprocal_arr = np.reciprocal(arr)
  
print(reciprocal_arr)


Python3
#  program to compute the Reciprocal for
# all elements in a given array with the
# help of numpy.reciprocal()
import numpy as np
  
arr = (3, 6.5, 1, 5.9, 8)
reciprocal_arr = np.reciprocal(arr)
  
print(reciprocal_arr)


输出:

示例 2:

Python

# PROGRAM TO FIND RECIPROCAL OF EACH
# ELEMENT OF NUMPY ARRAY
import numpy as np
  
tup = (12, 87, 77, 90, 57, 34)
arr = np.array(tup)
reciprocal_arr = 1/arr
  
print(reciprocal_arr)

输出:

方法二:使用 numpy.reciprocal() 方法

Numpy 库还提供了一种简单的方法来查找数组中每个元素的倒数。 reciprocal() 方法可以很容易地用于创建一个新数组,每个数组都包含每个元素的倒数。

示例 1:

Python3

#  program to compute the Reciprocal
# for all elements in a given array
# with the help of numpy.reciprocal()
import numpy as np
  
arr = [2, 1.5, 8, 9, 0.2]
reciprocal_arr = np.reciprocal(arr)
  
print(reciprocal_arr)

输出:

示例 2:

Python3

#  program to compute the Reciprocal for
# all elements in a given array with the
# help of numpy.reciprocal()
import numpy as np
  
arr = (3, 6.5, 1, 5.9, 8)
reciprocal_arr = np.reciprocal(arr)
  
print(reciprocal_arr)

输出: