3

在玩 NumPy 连接和范围构建对象r_时,我偶然发现了以下行为:显然,一个复杂的步骤,无论是真实的、虚构的还是适当的复杂,都以linspace类似的方式将其绝对值作为步数。

>>> import numpy as np
>>> 
>>> np.r_[0:12:4]           # start : stop : step
array([0, 4, 8])            # that's expected
>>> np.r_[0:12:4j]          # start : stop : imaginary step
array([ 0.,  4.,  8., 12.]) # that's in the docs
>>> np.r_[0:12:4+0j]        # real step of complex type ?
array([ 0.,  4.,  8., 12.]) # this is not as far as I can tell
# you can even do stuff like
>>> np.r_[0:12:-4+3j]        # proper complex step ?
array([ 0.,  3.,  6.,  9., 12.])

问:我只是想知道这是否是官方功能,因为我找不到它的文档。

为什么相关?好吧,r_主要是为了节省击键的便利,在某些情况下,此功能可以为您节省一些字符。

4

1 回答 1

4

该代码确实采用绝对值

if isinstance(step, complex):
    size.append(int(abs(step)))

但这不是书面保证。文档仅保证虚数的行为,而不是任意复数:

如果 step 是一个虚数(即 100j),那么它的整数部分被解释为所需的点数,并且包含 start 和 stop

您不应该依赖于非纯想象的复杂输入的行为,因为它不是文档化的保证。

也就是说,它可能是为了保证。我能够追踪的最远numpy.r_的代码就是这个提交。(这不是它的起源——我可以找到更早的参考资料scipy.r_——尽管找到了对 的参考资料,但scipy.r_我还是无法找到scipy.r_看起来将是正确的提交,除了 GitHub 似乎只有原始非 Git 提交的一部分。)

r_没有记录在我可以追踪到的最早提交中,但mgrid也出现在该提交中,并且mgrid复数的类似行为记录在该提交中

However, if the step length is a COMPLEX NUMBER (e.g. 5j), then the integer
part of it's magnitude is interpreted as specifying the number of points to
create between the start and stop values, where the stop value
IS INCLUSIVE.

我能够追踪的最远numpy.r_的文档是7 年后的这个提交,标记为“Merge from doc wiki”。我相信 doc wiki 现在已经消失了,我无法确定谁最初贡献了这些文档,但这些文档似乎不是基于numpy.r_'s author 的原始意图。

于 2018-02-23T03:36:11.357 回答