0

I often use NumPy arrays and have run into a problem. Many times, I do not care what the number of bits is to represent a type, but rather whether it is a floating point or not. For example, I would like to be able to write something like this:

import numpy as np

a = np.array([1.0, 2.0, 3.0])

if a.dtype is np.floating_type:
    print("I match all floating types! (np.float16, np.float32, np.float64, np.float, etc.)")

#or
if np.is_floating_point(a.dtype):
    print("I match all floating types! (np.float16, np.float32, np.float64, np.float, etc.)")

instead of the best method, I have found:


if a.dtype == np.float16 or a.dtype == np.float32 ...:
    print("I match all floating types! (np.float16, np.float32, np.float64, np.float, etc.)")

I have read some parts of NumPy's documentation but found nothing like this. Does anyone know if there exists such a function or class? For example, if all floating types are inherited from the same superclass, this issue would be resolved as all float types are floats, but with different amounts of bits. Adding a superclass might be overkill, so instead a function that checks if the type is any floating point type would be nice.

Here are some examples of what I have tried.

import numpy as np

a = np.array([1.0, 2.0, 3.0])

if a.dtype == np.floating:
    print("Works, as np.floating is float64")

a = np.array([1.0, 2.0, 3.0], dtype=np.float32)

if a.dtype == np.floating:
    print("Do not works, as np.floating is float64 ...")

edit

Answer:

if np.issubdtype(a.dtype, np.floating):
    print("Works as wanted :)")
    print("PS! Also works for the built-in float type.")
Databogdan
  • 11
  • 3

0 Answers0