What is the numpy.real_if_close() function in NumPy?

Overview

The real_if_close() function in NumPy is used to return real parts of an input array of complex values with all imaginary parts close to zero.

Syntax

np.real_if_close(a, tol=100)
Syntax of real_if_close() function

Parameters

The real_if_close() function takes the following parameter values:

  • a: This represents the input array. This is a required parameter.
  • tol: This represents the tolerance in machine epsilons for the complex part of the input array elements. This is a required parameter.
  • Note: Machine epsilons represent the smallest positive float value greater than zero.

Return value

The real_if_close() function returns a float if the input array has complex elements. If the input array is real, its data type is the same for the output.

Example

import numpy as np
# creating an input array
x = np.array([10.4 + 10e-14j, 15.5 + 15e-15j])
# defining the real_if_close() function
myarray = np.real_if_close(x, tol=1000)
print(myarray)

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an input array, x , using the array() function.
  • Line 7: We define the real_if_close() function on the input array, x . We assign the result to a variable myarray.
  • Line 9: We print the variable myarray.