Given a Numpy array/matrix, what is pythonic way to count the number of complex, pure real and pure imaginary number:
JavaScript
x
6
1
[[ 1. +0.j 1. +0.j 1. +0.j 1. +0.j 1. +0.j ]
2
[ 1. +0.j 0.309+0.951j -0.809+0.588j -0.809-0.588j 0.309-0.951j]
3
[ 1. +0.j -0.809+0.588j 0.309-0.951j 0.309+0.951j -0.809-0.588j]
4
[ 1. +0.j -0.809-0.588j 0.309+0.951j 0.309-0.951j -0.809+0.588j]
5
[ 1. +0.j 0.309-0.951j -0.809-0.588j -0.809+0.588j 0.309+0.951j]]
6
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:
JavaScript
1
11
11
1
np.count_nonzero(
2
np.logical_and(
3
np.logical_not(
4
np.equal(x.imag, 0)
5
),
6
np.logical_not(
7
np.equal(x.real, 0)
8
)
9
)
10
)
11
pure real
Use numpy.isreal
.
JavaScript
1
2
1
np.count_nonzero(np.isreal(x))
2
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:
JavaScript
1
9
1
np.count_nonzero(
2
np.logical_and(
3
np.logical_not(
4
np.equal(x.imag, 0)
5
),
6
np.equal(x.real, 0)
7
)
8
)
9