Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a number is a np.float64 or np.float32 or np.float16?

Tags:

python

numpy

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?

like image 886
Ginger Avatar asked Feb 03 '15 06:02

Ginger


People also ask

What is the difference between float64 and float32?

float32 is a 32 bit number - float64 uses 64 bits. That means that float64's take up twice as much memory - and doing operations on them may be a lot slower in some machine architectures. However, float64's can represent numbers much more accurately than 32 bit floats. They also allow much larger numbers to be stored.

What type is Numpy float64?

np. float64 is a class, not a function ( type(np.

Is float16 faster than float32?

NVIDIA GPUs can run operations in float16 faster than in float32, and TPUs can run operations in bfloat16 faster than float32.


1 Answers

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
like image 122
Andy Hayden Avatar answered Sep 22 '22 04:09

Andy Hayden