3

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 Answer 1

4
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.

Sign up to request clarification or add additional context in comments.

2 Comments

To be precise, it doesn't convert it creates a new array.
@juanpa.arrivillaga agreed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.