PyTorch是如何进行比较的?

yizd12fk  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(176)

我遇到了以下奇怪的问题,我不知道为什么会发生。我认为这与PyTorch如何在2的幂附近投出大值有关。谁能给予我一个提示?谢谢帮助!
第一次

j2cgzkjk

j2cgzkjk1#

事实证明,对于较大的值,Pytorch并不记录该值,而是记录它附近的某个值,这种近似值超出了本机float应该具有的值:

import torch
torch.set_printoptions(precision=10, sci_mode=False)

large_power_of_2 = 2**30
a = torch.zeros(3, 5)

for i in range(-10, 10):
    a[0][0] = large_power_of_2 + i
    print('try to print a[0]. Expected: {}, but real is {}'.format(large_power_of_2 + i, a[0][0]))

输出:

try to print a[0]. Expected: 1073741814, but real is 1073741824.0
try to print a[0]. Expected: 1073741815, but real is 1073741824.0
try to print a[0]. Expected: 1073741816, but real is 1073741824.0
try to print a[0]. Expected: 1073741817, but real is 1073741824.0
try to print a[0]. Expected: 1073741818, but real is 1073741824.0
try to print a[0]. Expected: 1073741819, but real is 1073741824.0
try to print a[0]. Expected: 1073741820, but real is 1073741824.0
try to print a[0]. Expected: 1073741821, but real is 1073741824.0
try to print a[0]. Expected: 1073741822, but real is 1073741824.0
try to print a[0]. Expected: 1073741823, but real is 1073741824.0
try to print a[0]. Expected: 1073741824, but real is 1073741824.0
try to print a[0]. Expected: 1073741825, but real is 1073741824.0
try to print a[0]. Expected: 1073741826, but real is 1073741824.0
try to print a[0]. Expected: 1073741827, but real is 1073741824.0
try to print a[0]. Expected: 1073741828, but real is 1073741824.0
try to print a[0]. Expected: 1073741829, but real is 1073741824.0
try to print a[0]. Expected: 1073741830, but real is 1073741824.0
try to print a[0]. Expected: 1073741831, but real is 1073741824.0
try to print a[0]. Expected: 1073741832, but real is 1073741824.0
try to print a[0]. Expected: 1073741833, but real is 1073741824.0

由于记录的数据相同,因此比较返回True。

相关问题