Python中的 numpy.reciprocal()
numpy.reciprocal()是一个数学函数,用于计算输入数组中所有元素的倒数。
Syntax :numpy.reciprocal(x, /, out=None, *, where=True)
Parameters :
x[array_like]: Input array or object whose elements needed to test.
out [ndarray, optional]: A location into which the result is stored.
–> If provided, it must have a shape that the inputs broadcast to.
–> If not provided or None, a freshly-allocated array is returned.
**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.
where [array_like, optional]: True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return :
y : ndarray. This is a scalar if x is a scalar.
注意:对于绝对值大于 1 的整数参数,由于Python处理整数除法的方式,结果始终为零。对于整数零,结果是溢出。
代码#1:
# Python3 code demonstrate reciprocal() function
# importing numpy
import numpy as np
in_num = 2.0
print ("Input number : ", in_num)
out_num = np.reciprocal(in_num)
print ("Output number : ", out_num)
输出 :
Input number : 2.0
Output number : 0.5
代码#2:
# Python3 code demonstrate reciprocal() function
# importing numpy
import numpy as np
in_arr = [2., 3., 8.]
print ("Input array : ", in_arr)
out_arr = np.reciprocal(in_arr)
print ("Output array : ", out_arr)
输出 :
Input array : [2.0, 3.0, 8.0]
Output array : [ 0.5 0.33333333 0.125 ]
代码 #3: reciprocal()函数中的异常。结果始终为零。
# Python3 code demonstrate Exception in reciprocal() function
# importing numpy
import numpy as np
in_arr = [2, 3, 8]
print ("Input array : ", in_arr)
out_arr = np.reciprocal(in_arr)
print ("Output array : ", out_arr)
输出 :
Input array : [2, 3, 8]
Output array : [0 0 0]