有没有办法显示正确的浮点值?

2024-04-24 12:51:47 发布

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

有没有像python3那样在python2中显示浮点值的方法?你知道吗

代码:

text = "print('hello, world')"

step = 100.0 / len(text)
result = 0.0

for _ in text:
    result += step

print result
print step
print result == 100.0

Python 2.7.9版

100.0
4.7619047619
False

Python 3.4.3版

99.99999999999997
4.761904761904762
False

我对结果变量感兴趣。不同步。对不起,我的解释不够充分。:)


Tags: 方法代码textinfalsehelloforworld
3条回答

repr显示更多的数字(我猜刚好可以重现相同的浮点):

>>> print result
100.0
>>> print repr(result)
99.99999999999997
>>> result
99.99999999999997

>>> print step
4.7619047619
>>> print repr(step)
4.761904761904762
>>> step
4.761904761904762

将十进制浮点数存储在二进制中会导致以十进制表示时出现舍入问题。这是任何语言(计算机编程)生活中的一个事实,但Python2处理这一点的方式与python3不同(参见:25898733)。你知道吗

使用string formatting可以使脚本在python2中生成与在python3中相同的输出,还可以生成更易读的输出:

text = "print('hello, world')"
step = 100.0 / len(text)
result = 0.0

for _ in text:
    result += step

print ("{0:.1f}".format(result))
print ("{0:.1f}".format(step))

print ("{0:.1f}".format(result) == "100.0")  # kludge to compare floats

输出

100.0
4.8
True

在Python2或Python3中运行代码会为resultstep计算相同的值。唯一的区别是浮点数的打印方式。你知道吗

在Python2.7(或Python3)中,您可以使用str.format控制小数点后显示的位数:

print('{:.14f}'.format(result))

印刷品

99.99999999999997

相关问题 更多 >