Reputation: 8650
This code
np.uint32( 1.13*100 )
returns 112
It should be 113.
How can I get around the strange rounding issue and make it return 113?
I am on numpy 1.9.1
Upvotes: 0
Views: 93
Reputation: 176998
If you can avoid it, don't cast the result of a floating point multiplication directly to an integer. Casting doesn't round the number to the nearest integer, it merely drops the decimal part of the float.
The problem is that floating point numbers are often only close approximations of real numbers. Arithmetical operations can exacerbate discrepancies. In your example:
>>> 1.13*100
112.99999999999999
The decimal part is dropped upon casting to an integer, leaving 112
.
It would be better to round the number to the nearest integer first (e.g. with np.round
) and then cast it to an integer type:
>>> np.int32(np.round(1.13*100))
113
Upvotes: 4