Skip to main content
 首页 » 编程设计

python之直接打印 `float32`和在Python中使用 `format()`函数的区别

2024年11月24日8开发

考虑以下 float :

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 

但是,当我使用 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 

如您所见,内部所有数字仍然存在,只是在使用某些显示方法时不显示。

我不认为这是一个错误,也不认为它会影响这些变量的计算结果;这似乎是正常的(和预期的)行为。