Python 3 奇怪的除法 [英] Python 3 strange division
问题描述
大约半小时思考我做错了什么!?"在 5 行代码上.. 因为 Python3 以某种方式四舍五入大整数.任何人都知道为什么会出现这样的问题:
Python2:
int(6366805760909027985741435139224001 # 这是 7**40./7) == 909543680129861140820205019889143 # 7**39
Python3:
int(6366805760909027985741435139224001/7) == 909543680129861204865300750663680 # 我不知道这是什么.
Python 3 不是舍入大整数".它的作用是在除法后返回一个浮点数.因此,在 Python 2 中:
<预><代码>>>>4/22在 Python 3 中:
<预><代码>>>>4/22.0原因很简单.在 Python 2 中,/
在使用整数时进行整数除法会产生一些令人惊讶的结果:
哎呀.在 Python 3 中这是固定的:
<预><代码>>>>5/22.5这意味着在 Python 3 中,你的除法返回一个浮点数:
<预><代码>>>>6366805760909027985741435139224001/79.095436801298612e+32此浮点数的准确度低于您需要的数字.然后,您使用 int()
将其转换为整数,您会得到一个意想不到的数字.
您应该改为使用整数除法(在 Python 2 和 Python 3 中):
<预><代码>>>>6366805760909027985741435139224001//7909543680129861140820205019889143L(尾随 L 表示它是一个长整数,在 Python 3 中长整数和普通整数合并了,所以没有尾随 L).
About half an hour thinking "what am i doing wrong!?" on the 5-lines code.. because Python3 is somehow rounding big integers. Anyone know why there is a problem such:
Python2:
int(6366805760909027985741435139224001 # This is 7**40.
/ 7) == 909543680129861140820205019889143 # 7**39
Python3:
int(6366805760909027985741435139224001
/ 7) == 909543680129861204865300750663680 # I have no idea what this is.
Python 3 is not "rounding big integers". What it does is that it will return a float after division. Hence, in Python 2:
>>> 4/2
2
while in Python 3:
>>> 4/2
2.0
The reason for this is simple. In Python 2, /
being integer division when you use integers have some surprising results:
>>> 5/2
2
Ooops. In Python 3 this is fixed:
>>> 5/2
2.5
This means that in Python 3, your division returns a float:
>>> 6366805760909027985741435139224001/7
9.095436801298612e+32
This float has less accuracy than the digits you need.
You then convert this to an integer with int()
, and you get a number you don't expect.
You should instead use integer division (in both Python 2 and Python 3):
>>> 6366805760909027985741435139224001//7
909543680129861140820205019889143L
(The trailing L means it's a long integer, in Python 3 the long and the normal integer is merged, so there is no trailing L).
这篇关于Python 3 奇怪的除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!