gpt4 book ai didi

带有 float 的字符串格式化的 Python 精度

转载 作者:太空狗 更新时间:2023-10-29 18:18:43 27 4
gpt4 key购买 nike

我不明白为什么在格式化包含浮点值的字符串时,最后一个字符串的精度没有得到遵守。即:

'%f' % 38.2551994324

返回:

'38.255199'

(丢失了 4 个标志!)

目前我解决了指定:

'%.10f' % 38.2551994324

它按预期返回“38.2551994324”……但我真的应该手动强制我想要多少个小数吗?有没有办法简单地告诉 python 保留所有这些?! (例如,如果我不知道我的号码有多少位小数,我该怎么办?)

最佳答案

但我真的应该手动强制我想要多少个小数吗?是的。

即使指定了 10 位十进制数字,您仍然不会打印所有这些数字。无论如何, float 没有那种精度,它们主要是十进制数的近似值(它们实际上是二进制分数相加)。试试这个:

>>> format(38.2551994324, '.32f')
'38.25519943239999776096738060005009'

还有更多您甚至没有指定的小数。

格式化 float 时(无论是 '%f' % number'{:f}'.format(number) 还是 format (number, 'f')),显示默认小数位数。这与使用 str()(或 '%s' % number'{}'.format(number)format(number),本质上是在底层使用了str(),只是默认包含的小数位数不同; 3.2 之前的 Python 版本在使用 str() 时使用 12 位数字表示整数

如果您希望您的有理数计算能够处理特定、精确 的位数,那么请不要使用 float 。使用 decimal.Decimal type相反:

  • Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – excerpt from the decimal arithmetic specification.

  • Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.

关于带有 float 的字符串格式化的 Python 精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20586011/

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