Typecasting to 'int' in Python generating wrong result

前端 未结 2 947
庸人自扰
庸人自扰 2021-01-19 07:34

I tried performing following typecast operation in Python 3.3

int( 10**23 / 10 )

Output: 10000000000000000000000

And after in

2条回答
  •  暖寄归人
    2021-01-19 07:54

    In Python 3.x, / always does true(floating point) division. Using floor division // instead could give you the expected result.

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

    The reason of this behavior is that float can't store big integers precisely.

    Assuming IEEE-754 double precision is used, it can store integers at most 253 precisely, which is approximitely 1016. Another example:

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

提交回复
热议问题