python中的精度浮点损失

2024-10-01 00:19:10 发布

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

我有一个叫做可变对数概率分数的列表。在

当我调用此函数时:

maxState = scores.pop(scores.index(max(scores)))

打印maxState,我意识到maxState失去了作为浮点的精度。有没有办法在不损失精度的情况下得到maxState?在

例句:我把分数表打印出来:[-35.7971525669589, -34.67875545008369] 打印maxState,我得到这个:-34.6787554501 (你可以看到它是圆形的)


Tags: 函数列表index对数精度概率pop分数
1条回答
网友
1楼 · 发布于 2024-10-01 00:19:10

您将字符串表示与实际内容混淆。任何地方都不会丢失精度,只有为写入控制台而生成的字符串使用的是舍入值,而不是显示所有数字。永远记住浮点数是数字近似值,而不是精确值。在

使用str()repr()函数时,Python浮点的格式不同;在列表或其他容器中,使用repr(),但直接打印并使用str()。在

如果您不喜欢这两个选项,请使用^{} function显式格式化它并指定精度:

print format(maxState, '.12f')

例如用8位小数打印出来。在

演示:

^{pr2}$

repr()输出是大致上是相当于使用'.17g'作为格式,而str()相当于{};这里的精度表示何时使用科学符号(e)和何时以浮点表示法(f)显示。在

我之所以说大致是,是因为repr()输出的目的是提供可往返的输出;请参见change notes for Python 3.1 on ^{} representation,其中后端口移植到Python2.7:

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.

相关问题 更多 >