5

I am looking for a way to check if a numpy array is np.float64 or np.float32. This works fine for np.float64:

a = np.random.rand(10)

if not issubclass(a.dtype.type, np.float):
    raise "Wrong type"  # No exception is raised for np.float64

But fails for np.float32:

a = np.random.rand(10).astype(np.float32)

if not issubclass(a.dtype.type, np.float):
    raise "Wrong type"  # An exception is raised!
slaw
  • 6,591
  • 16
  • 56
  • 109
  • Would `a.dtype.type in (np.float32, np.float64)` work? – user545424 May 17 '19 at 15:52
  • Yes, it would work and that was what we were planning to do but it seemed strange that `np.float32` and `np.float64` weren't both subclassed from `np.float`. We were going to go with `if not issubclass(a.dtype.type, (np.float32, np.float64, np.float)):` but this seems verbose – slaw May 17 '19 at 17:23
  • Well, on a 64 bit system the system type `float` is 64-bit so it kind of makes sense why numpy would not treat a 32 bit float as a subtype. – user545424 May 17 '19 at 18:54

1 Answers1

4

One way you can check if a data type is a float is with issubdtype:

In [1]: a = np.random.rand(10).astype(np.float64)

In [2]: b = np.random.rand(10).astype(np.float32)

In [3]: np.issubdtype(a.dtype,np.floating)
Out[3]: True

In [4]: np.issubdtype(b.dtype,np.floating)
Out[4]: True
user545424
  • 15,713
  • 11
  • 56
  • 70
  • I am getting: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. – slaw May 18 '19 at 04:49
  • Doesn't give me a warning with numpy version `1.13.3`. What version are you using? – user545424 May 18 '19 at 13:43
  • I also tested with version `1.17.0` and it works without warning. Are you sure you used `np.floating` and not `np.float`? – user545424 May 18 '19 at 14:24