Python和“任意精度整数” [英] Python and "arbitrary precision integers"

查看:319
本文介绍了Python和“任意精度整数”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Python整数范围中的答案,Python应该具有任意精度整数。但是,此结果显然是不是任意精度:

Python is supposed to have "arbitrary precision integers," according to the answer in Python integer ranges. But this result is plainly not arbitrary precision:

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

根据 PEP 237 bignum 任意大(不只是C的 long 类型的大小)。而维基百科说,Python的 bignum

According to PEP 237, bignum is arbitrarily large (not just the size of C's long type). And Wikipedia says Python's bignum is arbitrary precision.

那么为什么上述代码行中的结果不正确?

So why the incorrect result from the above line of code?

推荐答案

实际上在python3中,只要您将int进行除法,结果就会得到float。有一个 // 运算符执行整数除法:

Actually in python3 whenever you divide ints you get float as a result. There is a // operator that does integer division:

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

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

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

This does give the correct arbitrary precision output:

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



如何编写与python 2.2+和3.3兼容的代码



这实际上很简单,只需添加:

How to write code compatible with both python 2.2+ and 3.3

This is actually simple, just add:

 >>> from __future__ import division 

这将在2.2+代码中启用3.X部门。

this will enable 3.X division in 2.2+ code.

>>> 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'>

这篇关于Python和“任意精度整数”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆