python 浮点数
我有点困惑为什么 python 在这种情况下添加一些额外的十进制数,请帮忙解释一下
>>> mylist = ["list item 1", 2, 3.14]
>>> print mylist ['list item 1', 2, 3.1400000000000001]
i am kind of confused why python add some additional decimal number in this case, please help to explain
>>> mylist = ["list item 1", 2, 3.14]
>>> print mylist ['list item 1', 2, 3.1400000000000001]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
浮点数是一个近似值,它们不能精确地存储十进制数。因为它们试图仅用 64 位表示非常大范围的数字,所以它们必须在某种程度上进行近似。
意识到这一点非常重要,因为它会导致一些奇怪的副作用。例如,您可能非常合理地认为十手
0.1
的总和将为1.0
。虽然这看起来合乎逻辑,但对于浮点来说也是错误的:您可能会认为
n / m * m == n
。浮点世界再次不同意:或者也许同样奇怪的是,人们可能会认为对于所有
n
,n + 1 != n
。在浮点领域,数字不能像这样工作:请参阅 每个计算机科学家都应该了解浮点数,以获得对问题的精彩总结。
如果您需要精确的十进制表示,请查看 decimal 模块,它是 python 标准的一部分从 2.4 开始的库。它允许您指定有效数字的数量。缺点是,它比浮点慢得多,因为浮点运算是在硬件中实现的,而小数运算纯粹是在软件中进行的。它也有其自身的不精确问题,但如果您需要十进制数字的精确表示(例如对于金融应用程序),它是理想的选择。
例如:
Floating point numbers are an approximation, they cannot store decimal numbers exactly. Because they try to represent a very large range of numbers in only 64 bits, they must approximate to some extent.
It is very important to be aware of this, because it results in some weird side-effects. For example, you might very reasonably think that the sum of ten lots of
0.1
would be1.0
. While this seems logical, it is also wrong when it comes to floating point:You might think that
n / m * m == n
. Once again, floating-point world disagrees:Or perhaps just as strangely, one might think that for all
n
,n + 1 != n
. In floating point land, numbers just don't work like this:See What every computer scientist should know about floating point numbers for an excellent summary of the issues.
If you need exact decimal representation, check out the decimal module, part of the python standard library since 2.4. It allows you to specify the number of significant figures. The downside is, it is much slower than floating point, because floating point operations are implemented in hardware whereas decimal operations happen purely in software. It also has its own imprecision issues, but if you need exact representation of decimal numbers (e.g. for a financial application) it's ideal.
For example:
值得注意的是,Python 3.1 有一个新的浮点输出例程,它以预期的方式对其进行舍入(它也已向后移植到 Python 2.7):
来自 Python 3.1 中的新增功能 文档:
It is worthwhile to note that Python 3.1 has a new floating point output routine that rounds this in the expected manner (it has also been backported to Python 2.7):
From the What's New in Python 3.1 document:
如前所述,浮点数是一个近似值。
如果您想要精确性,可以使用小数(这是精确的表示):
http://docs.python.org/library/decimal.html
As mentioned before, it's all about floating points being an approximation.
If you want exactness you can use a decimal (which is a precise representation):
http://docs.python.org/library/decimal.html
我们可以通过以下命令修复它:
我添加来自@mark的答案
We can fix it by this command:
I add an answer from @mark