Skip to content
Advertisement

Count the number of complex, real and pure imaginary numbers in a numpy matrix

Given a Numpy array/matrix, what is pythonic way to count the number of complex, pure real and pure imaginary number:

[[ 1.   +0.j     1.   +0.j     1.   +0.j     1.   +0.j     1.   +0.j   ]
 [ 1.   +0.j     0.309+0.951j -0.809+0.588j -0.809-0.588j  0.309-0.951j]
 [ 1.   +0.j    -0.809+0.588j  0.309-0.951j  0.309+0.951j -0.809-0.588j]
 [ 1.   +0.j    -0.809-0.588j  0.309+0.951j  0.309-0.951j -0.809+0.588j]
 [ 1.   +0.j     0.309-0.951j -0.809-0.588j -0.809+0.588j  0.309+0.951j]]

Note: Please ignore the fact that complex numbers are superset of Imaginary and Real numbers.

Advertisement

Answer

complex

A number is complex if and only if its imaginary part is not zero, and its real part is not zero. Therefore:

np.count_nonzero(
    np.logical_and(
        np.logical_not(
            np.equal(x.imag, 0)
        ),
        np.logical_not(
            np.equal(x.real, 0)
        )
    )
)

pure real

Use numpy.isreal.

np.count_nonzero(np.isreal(x))

pure imaginary number

A number is pure imaginary if and only if:

  • its imaginary part is not zero, and
  • its real part is zero.

Therefore:

np.count_nonzero(
    np.logical_and(
        np.logical_not(
            np.equal(x.imag, 0)
        ),
        np.equal(x.real, 0)
    )
)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement