Python和“任意精度整数”

2024-04-23 17:17:05 发布

您现在位置:Python中文网/ 问答频道 /正文

根据Python integer ranges中的答案,Python应该具有“任意精度整数”。但这个结果显然是而不是任意精度:

$ python -c 'print("%d" % (999999999999999999999999/3))'
333333333333333327740928

根据PEP 237bignum是任意大的(不仅仅是C的long类型的大小)。而Wikipedia说Python的bignum是任意精度的。

那么为什么上面这行代码的结果不正确呢?


Tags: 答案代码类型精度整数integerwikipedialong
1条回答
网友
1楼 · 发布于 2024-04-23 17:17:05

实际上,在python3中,每当划分int时,结果会得到float。有一个//运算符执行整数除法:

 >>> 999999999999999999999999/3
 3.333333333333333e+23
 >>> 999999999999999999999999//3
 333333333333333333333333

 >>> type(999999999999999999999999/3)
 <class 'float'>
 >>> type(999999999999999999999999//3)
 <class 'int'>

这确实提供了正确的任意精度输出:

 python -c 'print("%d" % (999999999999999999999999//3))' 
 333333333333333333333333

如何编写与Python2.2+和3.3兼容的代码

这其实很简单,只需添加:

 >>> from __future__ import division 

这将在2.2+代码中启用3.X除法。

>>> from sys import version 
>>> version
'2.7.6 (default, Dec 30 2013, 14:37:40) \n[GCC 4.8.2]'
>>> from __future__ import division 
>>> type(999999999999999999999999//3)
<type 'long'>
>>> type(999999999999999999999999/3)
<type 'float'>

相关问题 更多 >