[Numpy-discussion] checking element types in array

Anne Archibald peridot.faceted@gmail....
Sat May 17 13:58:20 CDT 2008


2008/5/17 Zoho Vignochi <zoho.vignochi@gmail.com>:
> hello:
>
> I am writing my own version of a dot product. Simple enough this way:
>
> def dot_r(a, b):
>        return sum( x*y for (x,y) in izip(a, b) )
>
> However if both a and b are complex we need:
>
> def dot_c(a, b):
>        return sum( x*y for (x,y) in izip(a.conjugate(), b) ).real

As you probably realize, this will be vastly slower (ten to a hundred
times) than the built-in function dot() in numpy.

> I would like to combine these so that I need only one function which
> detects which formula based on argument types. So I thought that
> something like:
>
> def dot(a,b):
>        if isinstance(a.any(), complex) and isinstance(b.any(), complex):
>                return sum( x*y for (x,y) in izip(a.conjugate(), b) ).real
>        else:
>                return sum( x*y for (x,y) in izip(a, b) )
>
> And it doesn't work because I obviously have the syntax for checking
> element types incorrect. So my real question is: What is the best way to
> check if any of the elements in an array are complex?

numpy arrays are efficient, among other reasons, because they have
homogeneous types. So all the elements in an array are the same type.
(Yes, this means if you have an array of numbers only one of which
happens to be complex, you have to represent them all as complex
numbers whose imaginary part happens to be zero.) So if A is an array
A.dtype is the type of its elements.

numpy provides two convenience functions for checking whether an array
is complex, depending on what you want:

iscomplex checks whether each element has a nonzero imaginary part and
returns an array representing the element-by-element answer; so
any(iscomplex(A)) will be true if any element of A has a nonzero
imaginary part.

iscomplexobj checks whether the array has a complex data type. This is
much much faster, but of course it may happen that all the imaginary
parts happen to be zero; if you want to treat this array as real, you
must use iscomplex.

Anne


Anne


More information about the Numpy-discussion mailing list