Reputation: 11
I got a very wired test for python2.7 numpy array. Please look at this code.
import numpy as np
times = np.arange(5., 85, 0.1)
print times
times = np.array(times * 10, dtype=np.int)
print times
the original times
should be [5.0 ~ 84.9]
. After multiply 10, it should become [50 ~ 849]
, but result is like this:
[ 50 51 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 ... ]
There are two 51
between 50
and 52
Upvotes: 1
Views: 513
Reputation: 2115
The problem is, that your third entry isn't exactly 52.0
but 51.999999999999993
(see Is floating point math broken?). Truncating that value therefore results in 51
.
The correct way would be to first round the values. (As pointed out in Safest way to convert float to integer in python? all small enough integer numbers can be exactly expressed as a float.) You therefore have to calculate: times = np.array(np.round(times * 10), dtype=np.int)
Upvotes: 2