Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will casting an "integer" float to int always return the closest integer?

Tags:

python

I get a float by dividing two numbers. I know that the numbers are divisible, so I always have an integer, only it's of type float. However, I need an actual int type. I know that int() strips the decimals (i.e., floor rounding). I am concerned that since floats are not exact, if I do e.g. int(12./3) or int(round(12./3)) it may end up as 3 instead of 4 because the floating point representation of 4 could be 3.9999999593519561 (it's not, just an example).

Will this ever happen and can I make sure it doesn't?

(I am asking because while reshaping a numpy array, I got a warning saying that the shape must be integers, not floats.)

like image 403
cmeeren Avatar asked Nov 25 '15 13:11

cmeeren


1 Answers

Casting a float to an integer truncates the value, so if you have 3.999998, and you cast it to an integer, you get 3.

The way to prevent this is to round the result. int(round(3.99998)) = 4, since the round function always return a precisely integral value.

like image 171
Matt Timmermans Avatar answered Oct 03 '22 00:10

Matt Timmermans