简体   繁体   English

在Python中对'int'进行类型转换会产生错误的结果

[英]Typecasting to 'int' in Python generating wrong result

I tried performing following typecast operation in Python 3.3 我尝试在Python 3.3中执行以下类型转换操作

int( 10**23 / 10 ) int(10 ** 23/10)

Output: 10000000000000000000000 输出:10000000000000000000000

And after increasing power by one or further 并且在增加一个或更多的功率之后

int( 10**24 / 10 ) int(10 ** 24/10)

Output: 99999999999999991611392 输出:99999999999999991611392

int( 10**25 / 10 ) int(10 ** 25/10)

Output: 999999999999999983222784 输出:999999999999999983222784

Why is this happening? 为什么会这样? Although a simple typecasting like 虽然像一个简单的类型转换

int( 10**24 ) int(10 ** 24)

Output: 1000000000000000000000000 输出:1000000000000000000000000

is not affecting the values. 不影响价值观。

You are doing floating-point division with the / operator. 您正在使用/运算符进行浮点除法。 10**24/10 happens to have an inexact integer representation. 10 ** 24/10恰好有一个不精确的整数表示。

If you need an integer result, divide with //. 如果需要整数结果,则除以//。

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

In Python 3.x, / always does true(floating point) division. 在Python 3.x中, /始终执行true(浮点)除法。 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. 这种行为的原因是float无法精确存储大整数。

Assuming IEEE-754 double precision is used, it can store integers at most 2 53 precisely, which is approximitely 10 16 . 假设使用IEEE-754双精度,它可以精确地存储最多2 53的整数,大约为10 16 Another example: 另一个例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM