Typecasting to 'int' in Python generating wrong result

南笙酒味 提交于 2019-12-19 22:02:05

问题


I tried performing following typecast operation in Python 3.3

int( 10**23 / 10 )

Output: 10000000000000000000000

And after increasing power by one or further

int( 10**24 / 10 )

Output: 99999999999999991611392

int( 10**25 / 10 )

Output: 999999999999999983222784

Why is this happening? Although a simple typecasting like

int( 10**24 )

Output: 1000000000000000000000000

is not affecting the values.


回答1:


You are doing floating-point division with the / operator. 10**24/10 happens to have an inexact integer representation.

If you need an integer result, divide with //.

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



回答2:


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


来源:https://stackoverflow.com/questions/31883154/typecasting-to-int-in-python-generating-wrong-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!