[英]Difference between printing `float32` directly and using `format()` function in Python
考虑以下浮点数:
number = 2.695274829864502
当我打印它时,我得到:
print(number) # 2.695274829864502
当我将它转换为float32
我得到了截断的数字:
import numpy as np
number32 = np.float32(number)
print(number32) # 2.6952748
当我调用__repr__()
或__str__()
:
print(number32.__str__()) # 2.6952748
print(number32.__repr__()) # 2.6952748
但是,当使用 I format()
函数时,我得到了原始数字:
print("{}".format(number32)) # 2.695274829864502
它发生在Python3.5
和Python3.6
。 Python2.7
具有类似的行为,但对于更长的number
版本,它会截断 4 个尾随数字。
对此有何解释?
这可能只是显示的不同,这意味着, float32
类可能指定了不同的小数点后显示位数。
一些代码来突出差异:
n1 = 2.695274829864502
print()
print('n1 type ', type(n1))
print('n1 ', n1)
print('n1.__str__ ', n1.__str__())
print('n1.__repr__ ', n1.__repr__())
print('n1 {} ', '{}'.format(n1))
print('n1 {:.30f} ', '{:.30f}'.format(n1))
n2 = np.float32(n1)
print()
print('n2 type ', type(n2))
print('n2 ', n2)
print('n2.__str__ ', n2.__str__())
print('n2.__repr__ ', n2.__repr__())
print('n2 {} ', '{}'.format(n2))
print('n2 {:.30f} ', '{:.30f}'.format(n2))
n3 = np.float64(n1)
print()
print('n3 type ', type(n3))
print('n3 ', n3)
print('n3.__str__ ', n3.__str__())
print('n3.__repr__ ', n3.__repr__())
print('n3 {} ', '{}'.format(n3))
print('n3 {:.30f} ', '{:.30f}'.format(n3))
结果(使用Python 3.6
):
n1 type <class 'float'>
n1 2.695274829864502
n1.__str__ 2.695274829864502
n1.__repr__ 2.695274829864502
n1 {} 2.695274829864502
n1 {:.30f} 2.695274829864501953125000000000
n2 type <class 'numpy.float32'>
n2 2.6952748
n2.__str__ 2.6952748
n2.__repr__ 2.6952748
n2 {} 2.695274829864502
n2 {:.30f} 2.695274829864501953125000000000
n3 type <class 'numpy.float64'>
n3 2.695274829864502
n3.__str__ 2.695274829864502
n3.__repr__ 2.695274829864502
n3 {} 2.695274829864502
n3 {:.30f} 2.695274829864501953125000000000
如您所见,内部所有数字仍然存在,只是在使用某些显示方法时不显示。
我不认为这是一个错误或它会影响这些变量的计算结果; 这似乎是正常(和预期)的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.