max()未返回正确的最大numb

2024-04-25 14:23:02 发布

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

我使用以下代码来找出这两个数字中哪个值最大:

maximum = max(2.3,2.300000000001) 
print maximum

但是我得到的输出是2.3,而不是2.300000000001。有人能解释为什么会这样吗?你知道吗


Tags: 代码数字maxprintmaximum
3条回答

Python print命令自动截断数字。上面的评论中有一些解释。如果要打印完整值,请尝试使用print "%13f" % maximum显示完整值

别担心max没有坏,而且maximum确实持有2.300000000001print但是,在打印时会将其舍入。你可以用^{}来证明:

>>> maximum = max(2.3,2.300000000001) 
>>> print maximum
2.3
>>> print repr(maximum)
2.300000000001

the doc

14. Floating Point Arithmetic: Issues and Limitations

It’s easy to forget that the stored value is an approximation to the original decimal fraction, because of the way that floats are displayed at the interpreter prompt. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. If Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display

>>> 0.1

0.1000000000000000055511151231257827021181583404541015625

That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead

>>> 0.1

0.1

答:您得到的结果是好的,但print会使它更圆。你知道吗

您可以使用repr()检查实际值:

maximum = max(2.3,2.300000000001) 
print repr(maximum)

相关问题 更多 >