Convert complex to bool

When I try to convert a complex data to bool, I found the results are not what I expect.
For example:

>>> t = torch.tensor([1+1j, 0+1j, 1+0j])

and then I get this:

<ipython-input-3-666889c1a9fa>:1: UserWarning: Casting complex values to real discards the imaginary part (Triggered internally at  ../aten/src/ATen/native/Copy.cpp:239.)

tensor([ True,  True, False])

the result I expect is:

tensor([ True,  True,  True])

I just wonder why torch discard the imaginary part when converting complex to bool. Is bool type a kind of real type as the warning said?

As a comparison, here is the result of numpy:

>>> arr = np.array([1+1j, 0+1j, 1+0j])
>>> np.asarray(arr, bool)

array([ True,  True,  True])

My python version: ‘3.8.10’
torch version: ‘1.11.0+cu113’
numpy version: ‘1.21.0’

Yes, torch.bool is most likely seen as a “real” dtype as there is no “complex bool” type.
I don’t know the reasoning behind numpy’s interpretation, but could you explain what the transformation of cfloat into bool would represent and why numpy’s approach is the correct one (I’m not claiming PyTorch is right and I would be interested into a proper reasoning)?

Btw. I get tensor([ True, False, True]) which would be the expected output if only the real part is used.

Thanks :laughing:

I make this transformation because I want to get adjacent matrix from edge features data. The elements which are non-zero in edge features data indicate there are edges in corresponding positions. There are many methods to get adjacent matrix, I randomly chose this method and found this little problem by accident.

I don’t mean that numpy is correct. I thought pytorch and numpy have similar usage in similar api but it is not.

>>> t = torch.tensor([1+1j, 0+1j, 1+0j])
  tensor([1, 0, 1], dtype=torch.int32)
  tensor([ True, False,  True])

>>> arr = np.array([1+1j, 0+1j, 1+0j])
>>> arr.astype(int)
  /tmp/ipykernel_3548785/ ComplexWarning: Casting complex values to real 
  discards the imaginary part
  array([1, 0, 1])
>>> arr.astype(bool)
  array([ True,  True,  True])

It seems that torch.bool is indeed more like a real type in pytorch than bool in numpy.

Thanks for the follow up. Yeah, it might make sense to stick to numpy (but I don’t know which conversion makes more sense :slight_smile: ). Feel free to create a feature request on GitHub so that the code owners could discuss it.