# Return real parts if input is complex with all imaginary parts close to zero in Python

PythonNumpyServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

To return real parts if input is complex with all imaginary parts close to zero, use the numpy.real_if_close in Python. “Close to zero” is defined as tol * (machine epsilon of the type for a). If a is real, the type of a is used for the output. If a has complex elements, the returned type is float. The 1st parameter is a, the input array. The 2nd parameter is tol, Tolerance in machine epsilons for the complex part of the elements in the array.

## Steps

At first, import the required libraries −

import numpy as np

Creating a numpy array using the array() method −

arr = np.array([2.1 + 4e-14j, 5.2 + 3e-15j])


Display the array −

print("Our Array...\n",arr)

Check the Dimensions −

print("\nDimensions of our Array...\n",arr.ndim)


Get the Datatype −

print("\nDatatype of our Array object...\n",arr.dtype)

Get the Shape −

print("\nShape of our Array object...\n",arr.shape)


To return real parts if input is complex with all imaginary parts close to zero, use the numpy.real_if_close in Python. “Close to zero” is defined as tol * (machine epsilon of the type for a).

print("\nResult...\n",np.real_if_close(arr, tol = 1000))

## Example

import numpy as np

# Creating a numpy array using the array() method
arr = np.array([2.1 + 4e-14j, 5.2 + 3e-15j])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To return real parts if input is complex with all imaginary parts close to zero, use the numpy.real_if_close in Python
print("\nResult...\n",np.real_if_close(arr, tol = 1000))

## Output

Our Array...
[2.1+4.e-14j 5.2+3.e-15j]

Dimensions of our Array...
1

Datatype of our Array object...
complex128

Shape of our Array object...
(2,)

Result...
[2.1 5.2]
Updated on 01-Mar-2022 07:31:11