Python中意外的floatingpoint表示

2024-03-28 19:47:48 发布

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

您好,我正在使用Python中的一个字典来存储一些城市及其人口:

population = { 'Shanghai' : 17.8, 'Istanbul' : 13.3, 'Karachi' : 13.0, 'mumbai' : 12.5 }

现在,如果我使用命令print population,我得到的结果是:

^{pr2}$

而如果我使用命令print population['Shanghai'],我得到17.8的初始输入。在

我的问题是17.8和{}分别是如何变成{}和{}?所有这些信息是如何产生的?为什么它被存储在那里,因为我最初的输入表明我不需要额外的信息,至少据我所知。在


Tags: 命令信息字典人口populationprintshanghaipr2
3条回答

这在Python3.1中已经改变了。从what's new页:

Python now uses David Gay’s algorithm for finding the shortest floating point representation that doesn’t change its value. This should help mitigate some of the confusion surrounding binary floating point numbers.

The significance is easily seen with a number like 1.1 which does not have an exact equivalent in binary floating point. Since there is no exact equivalent, an expression like float('1.1') evaluates to the nearest representable value which is 0x1.199999999999ap+0 in hex or 1.100000000000000088817841970012523233890533447265625 in decimal. That nearest value was and still is used in subsequent floating point calculations.

What is new is how the number gets displayed. Formerly, Python used a simple approach. The value of repr(1.1) was computed as format(1.1, '.17g') which evaluated to '1.1000000000000001'. The advantage of using 17 digits was that it relied on IEEE-754 guarantees to assure that eval(repr(1.1)) would round-trip exactly to its original value. The disadvantage is that many people found the output to be confusing (mistaking intrinsic limitations of binary floating point representation as being a problem with Python itself).

The new algorithm for repr(1.1) is smarter and returns '1.1'. Effectively, it searches all equivalent string representations (ones that get stored with the same underlying float value) and returns the shortest representation.

The new algorithm tends to emit cleaner representations when possible, but it does not change the underlying values. So, it is still the case that 1.1 + 2.2 != 3.3 even though the representations may suggest otherwise.

The new algorithm depends on certain features in the underlying floating point implementation. If the required features are not found, the old algorithm will continue to be used. Also, the text pickle protocols assure cross-platform portability by using the old algorithm.

(Contributed by Eric Smith and Mark Dickinson; issue 1580)

你必须使用十进制。十进制如果你想让十进制完全按照你在世界上任何一台机器上指定的那样来表示。在

有关信息,请参阅Python手册:http://docs.python.org/library/decimal.html

>>> from decimal import Decimal
>>> print Decimal('3.14')
3.14

你需要了解浮点数在计算机中的工作原理。在

基本上,并不是所有的十进制数都可以精确地存储,在这些情况下,您将得到最接近的可能的数字。有时候这种抽象会泄露,你就会看到错误。在

这可能是由于您描述的两个用例所使用的打印逻辑的差异造成的。我无法重新生成该行为(在Win64中使用python2.7.2)。在

如果您使用一个完全可表示的数字,例如1.5,我想效果会消失。在

相关问题 更多 >