Saturday 15 January 2011

python - Correct way to test for numpy.dtype -



python - Correct way to test for numpy.dtype -

i'm looking @ third-party lib has next if-test:

if isinstance(xx_, numpy.ndarray) , xx_.dtype numpy.float64 , xx_.flags.contiguous: xx_[:] = ctypes.cast(xx_.ctypes._as_parameter_,ctypes.pointer(ctypes.c_double))

it appears xx_.dtype numpy.float64 fails:

>>> xx_ = numpy.zeros(8, dtype=numpy.float64) >>> xx_.dtype numpy.float64 false

what right way test dtype of numpy array float64 ?

this bug in lib.

dtype objects can constructed dynamically. , numpy time. there's no guarantee anywhere they're interned, constructing dtype exists give same one.

on top of that, np.float64 isn't dtype; it's a… i don't know these types called, types used build scalar objects out of array bytes, found in type attribute of dtype, i'm going phone call dtype.type. (note np.float64 subclasses both numpy's numeric tower types , python's numeric tower abcs, while np.dtype of course of study doesn't.)

normally, can utilize these interchangeably; when utilize dtype.type—or, matter, native python numeric type—where dtype expected, dtype constructed on fly (which, again, not guaranteed interned), of course of study doesn't mean they're identical:

>>> np.float64 == np.dtype(np.float64) == np.dtype('float64') true >>> np.float64 == np.dtype(np.float64).type true

the dtype.type will identical if you're using builtin types:

>>> np.float64 np.dtype(np.float64).type true

but 2 dtypes not:

>>> np.dtype(np.float64) np.dtype('float64') false

but again, none of guaranteed. (also, note np.float64 , float utilize exact same storage, separate types. , of course of study can create dtype('f8'), guaranteed work same dtype(np.float64), doesn't mean 'f8' is, or ==, np.float64.)

so, it's possible constructing array explicitly passing np.float64 dtype argument mean same instance when check dtype.type attribute, isn't guaranteed. , if pass np.dtype('float64'), or inquire numpy infer data, or pass dtype string parse 'f8', etc., it's less match. more importantly, definitely not np.float64 dtype itself.

so, how should fixed?

well, docs define means 2 dtypes equal, , that's useful thing, , think it's useful thing you're looking here. so, replace is ==:

if isinstance(xx_, numpy.ndarray) , xx_.dtype == numpy.float64 , xx_.flags.contiguous:

however, extent i'm guessing that's you're looking for. (the fact it's checking contiguous flag implies it's going go right internal storage… but why isn't checking c vs. fortran order, or byte order, or else?)

python numpy

No comments:

Post a Comment