np.where() has bug when handling zero element division in array

37 Views Asked by At

When i want to avoid the situation of zero encountered in divide, I used np.where(a != 0, b / a, 0) to judge this, and found a RuntimeWarning: divide by zero encountered in divide. This is wired, beacase i do the same operation in pytorch with tensor, it has no warning emerged. The test code shows below. Can anyone tell me why numpy came out this warning but the result is correct, whereas worked fine in pytorch?

a = torch.tensor([[[4, 0,], [4, 4]], [[3, 3,], [3, 3]]])
b = np.ones((2, 2, 2))
# print(a.shape)
b = torch.where(a != 0, b / a, 0)
print(b)

a = np.array([[[4, 0,], [4, 4]], [[3, 3,], [3, 3]]])
b = np.ones((2, 2, 2))
# print(a.shape)
b = np.where(a != 0, b / a, 0)
print(b)

and the results shows like blow:

tensor([[[0.2500, 0.0000],
         [0.2500, 0.2500]],

        [[0.3333, 0.3333],
         [0.3333, 0.3333]]], dtype=torch.float64)
private/test.py:77: RuntimeWarning: divide by zero encountered in divide
  b = np.where(a != 0, b / a, 0)
[[[0.25       0.        ]
  [0.25       0.25      ]]

 [[0.33333333 0.33333333]
  [0.33333333 0.33333333]]]
0

There are 0 best solutions below