范围生成器 `r_` - 具有复杂(但不是虚构)步骤的切片;使用幅度

range builder `r_` - slice with complex (but not imaginary) step; magnitude is used

玩 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_ 主要是为了节省击键方便,在某些情况下此功能可以为您节省几个字符。

The code does take the absolute value:

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

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

if step is an imaginary number (i.e. 100j) then its integer portion is interpreted as a number-of-points desired and the start and stop are inclusive

您不应依赖 not-purely-imaginary 复杂输入的行为,因为它没有书面保证。

也就是说,它可能是为了保证。我能够追踪到的最远 numpy.r_ 的代码是 this commit. (That's not where it originated - I can find references to scipy.r_ dating back even further - but despite finding references to scipy.r_, I have not been able to locate the code for scipy.r_, and I suspect neither the SciPy nor NumPy GitHub repositories contain the original code. It seems like this 将是正确的提交,除了 GitHub 似乎只有原始 [=40= 的片段]提交。)

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_ 的最远文档是 this commit 7 年后,标记为 "Merge from doc wiki"。我相信 doc wiki 现在已经消失了,我无法确定最初是谁贡献了这些文档,但这些文档似乎不是基于 numpy.r_ 作者的初衷。