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?
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?
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
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
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