Multiplication of an integer numpy array by a float number

Viewed 2609

I have a numpy array containing integer values. If I multiply once the whole matrix to a float number the result is a float matrix, but if I multiply column by column though a for loop, it gives only the integer parts.

import numpy as np
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = A

print("Multiplication as a whole matrix:")
A = 0.5*A
print(A)

for i in range(A.shape[1]):
    B[:,i] = 0.5*B[:,i]
    
print("Multiplication column by column:")
print(B)

If I change even only one element of the matrix to a float number (e.g. 1 to 1.0), both method gives the true result. I would like to know the underlying reason for that.

1 Answers
A = 0.5*A

Changes the whole array. When A.__rmul__(0.5) is called by the interpreter, it sees 0.5 is a float and thus creates a new A with dtype = float

for i in range(A.shape[1]):
    B[:,i] = 0.5*B[:,i]

Now, we're trying to read back B piecewise. But even though 0.5*B[:, i] is an array of floats, B is still dtype = int, so it casts the floats to int to fit in the existing B data structure.

Setting "even only one element of the matrix to a float" sets the whole array to dtype = float, and then casting to int will stop.

Related