gpt4 book ai didi

python - python中精度 float 的丢失

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:09 25 4
gpt4 key购买 nike

我有一个名为 scores of varying -log probabilities 的列表。

当我调用这个函数时:

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

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

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

最佳答案

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

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

如果您不喜欢任何一个选项,请使用 format() function 明确格式化它并指定精度:

print format(maxState, '.12f')

例如用 8 位小数打印它。

演示:

>>> maxState = -34.67875545008369
>>> repr(maxState)
'-34.67875545008369'
>>> str(maxState)
'-34.6787554501'
>>> format(maxState, '.8f')
'-34.67875545'
>>> format(maxState, '.12f')
'-34.678755450084'

repr() 输出大致相当于使用'.17g' 作为格式,而str() 等同于'.12g';这里的精度表示什么时候用科学计数法(e),什么时候用 float (f)显示。

我说大致是因为repr() 输出旨在为您提供可往返的输出;查看change notes for Python 3.1 on float() representation ,其中反向移植到 Python 2.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.

关于python - python中精度 float 的丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26441781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com