The iscomplexobj() function of NumPy module

Function signature:

iscomplexobj(object)

Parameters:

object – A Python object. A NumPy scalar or any Python container including a Numpy array.

Return value:

Returns True when the parameter passed is a complex type. Also returns True when a container passed in has at least one element as complex type.

Overview:

  • The NumPy function iscomplexobj() checks whether the parameter passed is a complex number. When the parameter is an ndarray or any other Python container the function iscomplexobj() checks whether the container has at least one element of complex type.

  • The behaviour of the NumPy function iscomplexobj() is different from the NumPy function iscomplex().The function iscomplexobj() returns True when the imaginary part of the complex number is zero. The isComplex() function returns True only when the imaginary part of the complex number is non-zero. The function iscomplexobj() returns True when one of the elements in a container(e.g. list, tuple) is a complex number. The function iscomplex() checks each element of an ndarray whether it is a complex number and returns the result as an ndarray of Boolean values.

Example 1:

# Example Python program that uses iscomplexobj() function
# to check whether an object is of complex type.
import numpy

c1 = 3+4j
result = numpy.iscomplexobj(c1)
print(result)

# Imaginary part is zero
c2 = 3-0j
result = numpy.iscomplexobj(c2)
print(result)

# Use the built-in function complex
c3 = complex(2, 2)
print(type(c3))
result = numpy.iscomplexobj(c3)
print(result)

# Use the numpy complex type
c4 = numpy.cdouble(1, -3)
print(type(c4))
result = numpy.iscomplexobj(c4)
print(result)

Output:

True

True

<class 'complex'>

True

<class 'numpy.complex128'>

True

Example 2:

The example uses a list, tuple and ndarray with a complex number as one of their elements and the function iscomplexobj() returns True when these instances are passed as arguments. The function iscomplexobj() returns False when the container is a set or a dict.

# Example Python program that checks whether
# a Python container has at least one complex
# number as its element
import numpy

# Working with a list
container1 = [1, complex(-5, -3)]
retVal = numpy.iscomplexobj(container1)
print(retVal)

# Working with a tuple
container2 = (1, -3-1j, 5.67)
retVal = numpy.iscomplexobj(container2)
print(retVal)

# The semantics of returning True when at-least one of the elements
# is complex number does not work on a set and dict
container3 = {-3-1j, 1, 2.1}
retVal = numpy.iscomplexobj(container3)
print(retVal)

# Working with a NumPy array
container4 = numpy.ndarray(shape = (1, 4), dtype = complex)
container4[0, 0] = 5.1
container4[0, 1] = 6-2j
container4[0, 2] = 7.2
container4[0, 3] = 8.3

retVal = numpy.iscomplexobj(container4)
print(retVal)

Output:

True

True

False

True

 


Copyright 2024 © pythontic.com