1

I trying to update the column of a matrix by multiplying it with a float. See the code below.

H = np.array([[1, 2, 3], [4, 5, 6]])
print(H[:, 0] * 0.1)
H[:, 0] = H[:, 0] * 0.1
print(H[:, 0])

Which gives the output:

[0.1 0.4]
[0 0]

Numpy seems to round the float 0.1 to 0, but only when assigning the value to the column. What is going on here?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
ViktorEM
  • 13
  • 2

1 Answers1

0

H has dtype np.int_. So when you multiply H[:, 0] * 0.1, the output is computed correctly and stored in an array of type np.float_. When you assign that float array back to H, it is cast to integer using trucation, hence the zero.

You can do any of the following to initialize H to a floating point type:

  • H = np.array([[1.0, 2, 3], [4, 5, 6]])
  • H = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float_)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • I just realized that the error didn't occur if I initialized H using floats instead. Thanks to your comment, I understand why! :) – ViktorEM Nov 16 '20 at 17:44
  • @ViktorEM. Feel free to select the answer if it answers your question. I've also updated with a couple of options you can use. – Mad Physicist Nov 16 '20 at 18:29