Reputation: 159
So I am trying to turn my float numpy array to integers. But when I do so:
array.astype(np.uint64)
it changes this array:
[ 550. 514. 451. 494. 490. 500. ...]
to this one:
[549 513 450 493 489 499 ... ]
So, I was wondering if any of you had an idea of why this is? I have to get np.uint64
as output for the code I am using next.
Thank you in advance.
Upvotes: 14
Views: 10793
Reputation:
As was said in comments, casting to integers does not round, it simply truncates the non-integer part. A float that appears as 550.
in console output may actually be 549.999999999
which will be truncated to 549
. Use rounding before typecasting. An example:
>>> a = np.array([5, 6, 7], dtype=float) - 1e-12
>>> a
array([ 5., 6., 7.])
>>> a.astype(np.uint64)
array([4, 5, 6], dtype=uint64)
>>> np.around(a).astype(np.uint64)
array([5, 6, 7], dtype=uint64)
Upvotes: 23