Typecasting to 'int' in python yielding wrong result

I tried to do the following type operation in Python 3.3

int (10 ** 23/10)

Output: 10000000000000000000000

And after increasing the power by one or more

int (10 ** 24/10)

Output: 99999999999999991611392

int (10 ** 25/10)

Output: 999999999999999983222784

Why is this happening? Although simple typing like

int (10 ** 24)

Output: 1000000000000000000000000

does not affect the values.

+3


source to share


2 answers


You are doing floating point division using the / operator. 10 ** 24/10 has imprecise integer representation.

If you want an integer result, split it by //.



>>> type(10**24/10)
<class 'float'>
>>> type(10**24//10)
<class 'int'>

      

+4


source


In Python 3.x, /

true (floating point) separation is always performed. Using gender division //

instead might give you the expected result.

>>> int(10**25 // 10)
1000000000000000000000000

      




The reason for this behavior is that it float

cannot store large integers accurately.

Assuming IEEE-754 is used , it can store integers at most 2 53 which is roughly 10 16 . Another example:

>>> int(10**17 / 10 + 1)
10000000000000000

      

+1


source







All Articles