The isreal() function of NumPy module

The isreal() function of NumPy module checks each element of a numpy array-like whether it is a real number. Real numbers include integers, rational numbers and irrational numbers.

Logical Operations Updated 25 Oct 2024 1 min read

Overview

  • The NumPy function isreal() checks each the element of a NumPy array-like, whether the element is a real number. If the element is a real number, the result of the test is True. The result is False otherwise. The results are returned as a Boolean array. If the input to the function is a scalar a single Boolean value is returned.
  • Real numbers are subset of complex numbers. Hence, the function isreal() will return True for a complex number whose imaginary part is zero. Whereas, the iscomplex() function will return True only if the complex number has a non-zero imaginary part.

Example

python
# Example Python program that checks elements

            # of a NumPy.ndarray whether they belong to real numbers

            # using numpy.isreal()

            import math

            import numpy

# Create an ndarray

            numbers = numpy.ndarray(shape = (2, 4),

                                    dtype = complex)

# Populate the ndarray with a mix of numbers including integers,

            # rational numbers, irrational numbers and complex numbers

# Integers

            r1 = -1

            r2 = 3

# Rational numbers

            r3 = 3/4

            r4 = 1/3

# Irrational numbers

            r5 = 1/7

            r6 = math.sqrt(2)

# Complex numbers

            c1 = 10+0j

            c2 = 1-2j

numbers[0][0] = r1

            numbers[0][1] = r2

            numbers[0][2] = r3

            numbers[0][3] = r4

numbers[1][0] = r5

            numbers[1][1] = r6

            numbers[1][2] = c1

            numbers[1][3] = c2

print("Numbers:")

            print(numbers)

            print("Numpy.isreal() results:")

            results = numpy.isreal(numbers)

            print(results)

Output

Output
Numbers:

[[-1.        +0.j  3.        +0.j  0.75      +0.j  0.33333333+0.j]

 [ 0.14285714+0.j  1.41421356+0.j 10.        +0.j  1.        -2.j]]

Numpy.isreal() results:

[[ True  True  True  True]

 [ True  True  True False]]