python 浮点数,为什么打印结果不一样(给出例子)?

python floating point, why is the print result different (examples given)?

a = (random.random(), random.random())

打印(a)

打印(a[0])

结果是:

(0.4817527913069962, 0.7017598562799067)

0.481752791307

打印元组(列表的类似行为)背后发生了什么额外的事情?为什么会有多余的分数?

非常感谢。

顺便说一句,这是 python 2.7

您看到的是 str(float)repr(float) 所做的格式选择之间的差异。 Python 2.x, str(float) returns 12位,而 repr(float) returns 17位。在其交互模式下,Python 使用 str() 来格式化结果。这说明了格式化浮点数时的 12 位精度。但是当结果是元组或列表时,字符串格式化逻辑使用 repr() 来格式化每个元素。

repr(float) 的输出必须能够转换回原始值。使用 17 位精度可以保证这种行为。 Python 3 使用更复杂的算法,returns 最短的字符串将返回到原始值。由于 repr(float) 经常 returns 一个更友好的出现结果, str(float) 被更改为与 repr(float) 相同。