1

When I use numpy arange function to build a numpy array, the size is not right when use shape to check. For example, if I build an array: np.arange(-5,6,1), the shape is (11,). However, when I build array:np.arange(-0.001,0.0011,0.0001), the shape is (22,)

The shape find with np.array.shape

hpaulj
  • 221,503
  • 14
  • 230
  • 353
jmin
  • 15
  • 3
  • Should it be -0.0001, instead of -0.001? – Jzou Jan 10 '20 at 22:44
  • Did you read the docs? **When using a non-integer step, such as 0.1, the results will often not be consistent.** – hpaulj Jan 10 '20 at 23:35
  • thanks, I am going to read . – jmin Jan 10 '20 at 23:47
  • I read docs and it said:"When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases" when I use numpy.linspace,it works. thanks for your suggestion! – jmin Jan 10 '20 at 23:56

1 Answers1

0

It looks like when you print the array, you get this -

array([-1.00000000e-03, -9.00000000e-04, -8.00000000e-04, -7.00000000e-04,
       -6.00000000e-04, -5.00000000e-04, -4.00000000e-04, -3.00000000e-04,
       -2.00000000e-04, -1.00000000e-04,  4.33680869e-19,  1.00000000e-04,
        2.00000000e-04,  3.00000000e-04,  4.00000000e-04,  5.00000000e-04,
        6.00000000e-04,  7.00000000e-04,  8.00000000e-04,  9.00000000e-04,
        1.00000000e-03,  1.10000000e-03])

It looks like there are some rounding issues when -0.001 gets incremented by 0.0001 suggested by the value 4.33680869e-19 when it should be 0. This means that each subsequent value in the array is slightly less than what is shown. That is why the last value, 0.0011, is included in the array when it shouldn't. This is what is giving you the shape mismatch.

I recommend doing this so that rounding doesn't become an issue.

x = np.arange(-10,11,1)
x = x/10000
x.shape # gets (21,)
print(x)
Richard X
  • 1,119
  • 6
  • 18
  • You are right. The array is what i got. that should be (21,) but it is (22,). thanks for your solution. – jmin Jan 10 '20 at 22:35
  • According to Hpaulj suggestion, I read docs and it said that numpy.linspace can be used. I tried and found it works well. so I would like to use numpy.linspace when I try to build numpy array with decimal start and end. – jmin Jan 11 '20 at 00:03