2

I am learning Python and SciPy. I met below two expressions:

a = np.concatenate(([3], [0]*5, np.arange(-1, 1.002, 2/9.0)))

and

b = np.r_[3,[0]*5,-1:1:10j]

The two expressions output the same array. I don't understand 10j in the 2nd expression. What is its value? Thanks a lot for help.

Praveen
  • 6,872
  • 3
  • 43
  • 62

2 Answers2

3

It's a shorthand for creating an np.linspace.

As per the docs for np.r_:

If slice notation is used, the syntax start:stop:step is equivalent to np.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 words start:stop:stepj is interpreted as np.linspace(start, stop, step, endpoint=1) inside of the brackets.

So for your specific case, -1:1:10j would result in a step size of (1 - (-1)) / 9 = 0.222222... which gives the following array:

>>> np.r_[-1:1:10j]
array([-1.        , -0.77777778, -0.55555556, -0.33333333, -0.11111111,
        0.11111111,  0.33333333,  0.55555556,  0.77777778,  1.        ])

While this happens to give you the same answer as np.arange(-1, 1.002, 2/9.0), note that arange is not a good way to create such an array in general, because using non-integer step-sizes in aranges is a 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.

Praveen
  • 6,872
  • 3
  • 43
  • 62
0

Here you go: Quote from https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html

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.

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38
  • Thanks AnonyXous for the link. I did several tests using Jupityer notebook and found something which is not entirely like what the content in the link. See one example text below: np.linspace(-1, 1, 10, endpoint=True) (the same as np.r_[-1:1:10j]). The produced array has 10 elements. So 10 should the number of elements, not step in np.linspace(start, stop, step, endpoint=1). Am I right? – Linda Zhang Feb 23 '18 at 15:10