Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python strange int behavior

Tags:

python

int

Take a look at this:

print 41063625 ** (1.0/3)  # cube-root(41063625) = 345
print int(345.0)
print int(41063625 ** (1.0/3))

It outputs:

345.0
345
344

I was expecting the last line to be 345, since I was expecting int(41063625 ** (1.0/3)) to equal int(345.0) to in turn equal 345, as the other two outputs suggest. However, this is evidently not the case. Can anyone give me any insight as to what's going on here?

like image 658
arshajii Avatar asked Nov 10 '12 13:11

arshajii


2 Answers

Print (or rather float.__str__) is rounding the output.

In [22]: str( 41063625 ** (1.0/3) )
Out[22]: '345.0'

The floating point representation for 41063625 ** (1.0/3) is less than 345, so when you take the int of it, you get 344 rather than 345.

In [15]: 41063625 ** (1.0/3)
Out[15]: 344.9999999999999

In [16]: int(345.0)
Out[16]: 345

In [17]: int(41063625 ** (1.0/3))
Out[17]: 344

If you want the closest int, you could use round:

In [18]: round(41063625 ** (1.0/3))
Out[18]: 345.0

or, to get an int:

In [19]: int(round(41063625 ** (1.0/3)))
Out[19]: 345
like image 105
unutbu Avatar answered Nov 17 '22 19:11

unutbu


because 41063625 ** (1.0/3) is not 345.0:

In [7]: 41063625 ** (1.0/3)
Out[7]: 344.9999999999999

In [8]: int(344.9999999999999)
Out[8]: 344
like image 31
Ashwini Chaudhary Avatar answered Nov 17 '22 17:11

Ashwini Chaudhary