11

(版本 1.13+)中有一个positive函数numpy,它似乎什么也没做:

In [1]: import numpy as np                                                                               

In [2]: A = np.array([0, 1, -1, 1j, -1j, 1+1j, 1-1j, -1+1j, -1-1j, np.inf, -np.inf])                     

In [3]: A == np.positive(A)                                                                              
Out[3]: 
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True])

文档说:Returned array or scalar: `y = +x`

该功能的用例是什么?

4

2 回答 2

1

此功能的用例可能很少。提供它是因为每个 python 运算符都在 numpy 中作为 ufunc 公开:

  • 一元+np.positive
  • 一元-np.negative
  • 二进制+np.add
  • 二进制-np.subtract
  • ETC ...

正如文档所述,并在另一个答案中指出,np.positive复制数据,就像这样np.copy做一样,但有两个警告:

  1. 它可以改变dtype输入的

  2. 它仅针对算术类型定义。例如,如果您尝试在布尔数组上调用它,您将得到

     UFuncTypeError: ufunc 'positive' did not contain a loop with signature matching types dtype('bool') -> dtype('bool')
    

另一件事是,因为positive是 a ufunc,所以它可以就地工作,使其成为算术类型的有效无操作函数:

np.positive(x, out=x)
于 2020-09-28T16:25:54.483 回答
0

如果你有一个向量x,然后np.positive(x)给你,+1*(x)然后np.negative(x)给你-1*(x)

np.positive([-1,0.7])

output: array([-1. ,  0.7])


np.negative([-1.5,0.7])

output:array([ 1.5, -0.7])


np.positive(np.array([0, 1, -1, 1j, -1j, 1+1j, 1-1j, -1+1j, -1-1j, np.inf, -np.inf]))

output: array([  0.+0.j,   1.+0.j,  -1.+0.j,   0.+1.j,  -0.-1.j,   1.+1.j,
         1.-1.j,  -1.+1.j,  -1.-1.j,  inf+0.j, -inf+0.j])


np.negative(np.array([0, 1, -1, 1j, -1j, 1+1j, 1-1j, -1+1j, -1-1j, np.inf, -np.inf]))

output: array([ -0.-0.j,  -1.-0.j,   1.-0.j,  -0.-1.j,   0.+1.j,  -1.-1.j,
        -1.+1.j,   1.-1.j,   1.+1.j, -inf-0.j,  inf-0.j])


用例取决于。一旦用例成为x1 = copy(x). 它会创建一个重复的数组供您使用。

于 2020-04-21T04:49:55.563 回答