gpt4 book ai didi

python - 将float转换为str时如何检查默认小数精度?

转载 作者:IT老高 更新时间:2023-10-28 20:41:59 34 4
gpt4 key购买 nike

float转换成str时,可以指定要显示的小数位数

'%.6f' % 0.1
> '0.100000'
'%.6f' % .12345678901234567890
> '0.123457'

但是当简单地在 python 2.7 中的 float 上调用 str 时,它似乎默认为最多 12 个小数点

str(0.1)
>'0.1'
str(.12345678901234567890)
>'0.123456789012'

定义/记录的最大小数点数在哪里?我可以通过编程方式获取此号码吗?

最佳答案

显示的小数位数会有很大差异,并且无法预测在纯 Python 中将显示多少个小数。 numpy 等一些库允许您设置输出精度。

这仅仅是因为 limitations of float representation .

链接的相关部分讲述了 Python 如何选择显示 float 。

Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine

Python keeps the number of digits manageable by displaying a rounded value instead

现在,这里有重叠的可能性:

Interestingly, there are many different decimal numbers that share the same nearest approximate binary fraction

选择显示哪些十进制值的方法在 Python 3.1 中发生了变化(但最后一句话暗示这可能是一个实现细节)。

For example, the numbers 0.1 and 0.10000000000000001 are bothapproximated by 3602879701896397 / 2 ** 55. Since all of these decimalvalues share the same approximation, any one of them could bedisplayed while still preserving the invariant eval(repr(x)) == x

Historically, the Python prompt and built-in repr() function wouldchoose the one with 17 significant digits, 0.10000000000000001.Starting with Python 3.1, Python (on most systems) is now able tochoose the shortest of these and simply display 0.1.

关于python - 将float转换为str时如何检查默认小数精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51728576/

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