The isreal() function of NumPy module

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 zeroWhereas, the iscomplex() function will return True only if the complex number has a non-zero imaginary part.

Example:

# 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:

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]]

 


Copyright 2024 © pythontic.com