考虑以下浮点数:
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
如您所见,内部所有数字仍然存在,使用某些显示方法时没有显示它们。
我不认为这是一个错误,也不会影响这些变量的计算结果;这似乎是正常(和预期的)行为。