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

2024-10-03 13:31:13 发布

您现在位置: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

但是,当使用Iformat()函数时,我会得到原始数字:

print("{}".format(number32)) # 2.695274829864502

它发生在Python3.5Python3.6中。Python2.7具有类似的行为,只是对于number的较长版本,它会截断4个尾随数字。你知道吗

对此有何解释?你知道吗


Tags: 函数importnumpynumberasnp数字print
1条回答
网友
1楼 · 发布于 2024-10-03 13:31:13

这可能只是显示的不同,也就是说,类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

正如您所看到的,内部所有的数字仍然存在,它们只是在使用某些显示方法时不显示。你知道吗

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

相关问题 更多 >