2024-04-23 17:17:05 发布
网友
根据Python integer ranges中的答案,Python应该具有“任意精度整数”。但这个结果显然是而不是任意精度:
$ python -c 'print("%d" % (999999999999999999999999/3))' 333333333333333327740928
根据PEP 237,bignum是任意大的(不仅仅是C的long类型的大小)。而Wikipedia说Python的bignum是任意精度的。
bignum
long
那么为什么上面这行代码的结果不正确呢?
实际上,在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
这其实很简单,只需添加:
>>> 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'>
实际上,在python3中,每当划分int时,结果会得到float。有一个
//
运算符执行整数除法:这确实提供了正确的任意精度输出:
如何编写与Python2.2+和3.3兼容的代码
这其实很简单,只需添加:
这将在2.2+代码中启用3.X除法。
相关问题 更多 >
编程相关推荐