我正在学习 Python 和 SciPy。我遇到了以下两个表达式:
a = np.concatenate(([3], [0]*5, np.arange(-1, 1.002, 2/9.0)))
和
b = np.r_[3,[0]*5,-1:1:10j]
两个表达式输出相同的数组。我不明白第二个表达式中的 10j。它的值(value)是多少?非常感谢您的帮助。
请您参考如下方法:
这是创建 np.linspace 的简写.
根据 docs for np.r_ :
If slice notation is used, the syntax
start:stop:stepis equivalent tonp.arange(start, stop, step)inside of the brackets. However, 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. In other wordsstart:stop:stepjis interpreted asnp.linspace(start, stop, step, endpoint=1)inside of the brackets.
因此,对于您的特定情况,-1:1:10j 将导致步长为 (1 - (-1))/9 = 0.222222... 从而给出以下数组:
>>> np.r_[-1:1:10j]
array([-1. , -0.77777778, -0.55555556, -0.33333333, -0.11111111,
0.11111111, 0.33333333, 0.55555556, 0.77777778, 1. ])
虽然这碰巧给您的答案与np.arange(-1, 1.002, 2/9.0)相同,但请注意arange 通常不是创建这样一个数组的好方法,因为在aranges 中使用非整数步长是bad idea :
When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases.
