So I was made aware that the following two snippets produce arrays [0, 0.001, 0.002...]. Which of the two ways of creating arrays would be best practice and what are the differences? Why does np.r_[0:1:0.001] work if it is supposed to be used for row-wise concatenations?
a = np.arange(0, 1, 0.001)
b = np.r_[0:1:0.001]
I am also wondering why this prints false even though they are both type: numpy.ndarray.
if b is a:
print(True)
else:
print(False)
CodePudding user response:
np.arange
and np.linspace
are the basic functions for creating regularly spaced values. Learn their differences. Pay attention to arange
warnings about fractional steps.
Novices often are bothered about floating point issues, such as when they view np.arange(0,1,.1).tolist()
.
np.r_
(and np.c_
, np.ogrid
, np.mgrid
) uses indexing syntax to give you access to concatenation and ranges. It isn't superior; it's just different, and may be convenient.
With np.r_[0:1:0.001]
it does call arange
just as you do. with '0:1:11' it will use linspace
. And the concatenation functionality lets you do something like:
In [19]: np.r_[0:3, 3:5:5j]
Out[19]: array([0. , 1. , 2. , 3. , 3.5, 4. , 4.5, 5. ])
In [20]: np.concatenate((np.arange(3),np.linspace(3,5,5)))
Out[20]: array([0. , 1. , 2. , 3. , 3.5, 4. , 4.5, 5. ])
If arange
(and linspace
) does what you want, there's no need to use np.r_
.
CodePudding user response:
is
is not the right comparison tool. You would also get False
with:
a = np.arange(0, 1, 0.001)
b = np.arange(0, 1, 0.001)
a is b
# False
This simply means that the objects are not the same, not that their values is different
Use numpy.allclose
:
a = np.arange(0, 1, 0.001)
b = np.r_[0:1:0.001]
np.allclose(a,b)
Output: True