Why python truncation floats to integers?

Viewed 53

I am wondering why Python truncates the numbers to integers whenever I assign floating point numbers to a numpy array:

import numpy as np

lst = np.asarray(list(range(10)))

print ("lst before assignment: ", lst)
lst[:4] = [0.3, 0.5, 10.6, 0.2];
print ("lst after assignment: ", lst)

output:

lst before assignment:  [0 1 2 3 4 5 6 7 8 9]
lst after assignment:  [ 0  0 10  0  4  5  6  7  8  9]

Why does it do this? Since you do not need to specify types in the language, I cannot understand why numpy would cast the floats to ints before assigning to the array (which contains integers).

2 Answers

Try:

lst = np.asarray(list(range(10)), dtype=float)
lst before assignment:  [0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
lst after assignment:  [ 0.3  0.5 10.6  0.2  4.   5.   6.   7.   8.   9. ]

numpy defines the data type or .dtype of the array at the moment of creation. The program understands that you are storing integers and once it is specified as such it stays that way. If you plan to use floats you should either input floats or specify it in the data type, i.e.

np.array(list(map(float, range(10)))

or

np.array(list(range(10)), dtype=np.float)

or

np.array(list(range(10)).astype(np.float)
Related