31

Other than using a set of or statements

isinstance( x, np.float64 ) or isinstance( x, np.float32 ) or isinstance( np.float16 )

Is there a cleaner way to check of a variable is a floating type?

sau
  • 1,316
  • 4
  • 16
  • 37
Ginger
  • 8,320
  • 12
  • 56
  • 99

3 Answers3

62

You can use np.floating:

In [11]: isinstance(np.float16(1), np.floating)
Out[11]: True

In [12]: isinstance(np.float32(1), np.floating)
Out[12]: True

In [13]: isinstance(np.float64(1), np.floating)
Out[13]: True

Note: non-numpy types return False:

In [14]: isinstance(1, np.floating)
Out[14]: False

In [15]: isinstance(1.0, np.floating)
Out[15]: False

to include more types, e.g. python floats, you can use a tuple in isinstance:

In [16]: isinstance(1.0, (np.floating, float))
Out[16]: True
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
5

To check numbers in numpy array, it provides 'character code' for the general kind of data.

x = np.array([3.6, 0.3])
if x.dtype.kind == 'f':
    print('x is floating point')

See other kinds of data here in the manual.

Be careful when using isinstance and is operator to determine type of numbers.

import numpy as np
a = np.array([1.2, 1.3], dtype=np.float32)

print(isinstance(a.dtype, np.float32))     # False
print(isinstance(type(a[0]), np.float32))  # False
print(a.dtype is np.float32)               # False
print(type(a[0]) is np.dtype(np.float32))  # False

print(isinstance(a[0], np.float32))        # True
print(type(a[0]) is np.float32)            # True
print(a.dtype == np.float32)               # True
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
MEOWWWWWWWW
  • 175
  • 2
  • 9
1

The best way to a check if a NumPy array is in floating precision whether 16,32 or 64 is as follows:

import numpy as np
a = np.random.rand(3).astype(np.float32)
print(issubclass(a.dtype.type,np.floating))

a = np.random.rand(3).astype(np.float64)
print(issubclass(a.dtype.type,np.floating))

a = np.random.rand(3).astype(np.float16)
print(issubclass(a.dtype.type,np.floating))

In this case all will be True.

The common solution however can be give wrong outputs as shown below,

import numpy as np
a = np.random.rand(3).astype(np.float32)
print(isinstance(a,np.floating))

a = np.random.rand(3).astype(np.float64)
print(isinstance(a,np.floating))

a = np.random.rand(3).astype(np.float16)
print(isinstance(a,np.floating))

In this case all will be False

The workaround for above though is

import numpy as np
a = np.random.rand(3).astype(np.float32)
print(isinstance(a[0],np.floating))

a = np.random.rand(3).astype(np.float64)
print(isinstance(a[0],np.floating))

a = np.random.rand(3).astype(np.float16)
print(isinstance(a[0],np.floating))

Now all will be True

Mohit Lamba
  • 1,194
  • 13
  • 30
  • 1
    I like the `issubclass` approach. The `a[0]` workaround is only effective for 1D data since for higher dimensions it'll return an array. – Brian Hawkins Apr 14 '23 at 00:07