In this article, we implement the NumPy real_if_close function of the NumPy package in python. Numpy consists of functions that can be utilized to perform operations on an array, numpy real_if_close returns the real part of a complex imaginary input. Below understand the syntax of NumPy real_if_close and implements a few of its examples.
What is NumPy real_if_close?
If the input is complex with all imaginary parts close to zero, we use numpy.real_if_close
to return real parts of the input. “Close to zero” is defined as tol*(machine epsilon of the type for a). The return type is float if a has complex elements where a is the input array.
Note: Machine epsilons represent the smallest positive float value greater than zero.
Syntax
np.real_if_close(a, tol=)
Parameters
Parameter | Description | Required/Optional |
a | input array | Required |
tol | tolerance in machine epsilons for the complex part of the input array elements | Required |
Return Value: If the input array has complex elements real_if_close()
returns a float value.
Examples of NumPy real_if_close
Start by importing numpy
import numpy as np
arr = np.array([2.1 + 4e-14j, 5.2 + 3e-15j,10.4 + 10e-14j,15.5 + 15e-15j])
Displaying the details of the array
print("Input Array: \n",arr)
print("\nDimensions of input array: \n",arr.ndim)
print("\nDatatype of input array: \n",arr.dtype)
print("\nShape of input array: \n",arr.shape)
Output :
Input Array:
[ 2.1+4.0e-14j 5.2+3.0e-15j 10.4+1.0e-13j 15.5+1.5e-14j]
Dimensions of input array:
1
Datatype of input array:
complex128
Shape of input array:
(4,)
Example 1: Sample testing of numpy real_if_close
print("\n Result: \n",np.real_if_close(arr, tol = 1000))
Here, the output will contain all the real parts of the elements of the array arr
since all the imaginary parts are too small.
Output :
Result:
[ 2.1 5.2 10.4 15.5]
Example 2: When the imaginary numbers are not close to zero.
import numpy as np
arr = np.array([1+5j,3-6j])
# Displaying teh deatils of array
print("Input Array: \n",arr)
print("\nDimensions of input array: \n",arr.ndim)
print("\nDatatype of input array: \n",arr.dtype)
print("\nShape of input array: \n",arr.shape)
# implementing numpy.real_if_close in Python
print("\nResult...\n",np.real_if_close(arr, tol = 1000))
Since here the imaginary parts are significantly large, np.real_if_close()
returns back the original complex numbers.
Output :
Input Array:
[1.+5.j 3.-6.j]
Dimensions of input array:
1
Datatype of input array:
complex128
Shape of input array:
(2,)
Result...
[1.+5.j 3.-6.j]
Conclusion
In this article, we came across the theoretical and practical implementation of Numpy real_if_close(), a function of NumPy in Python. This function helps to return real parts of input with data type float. Given the input is complex with all imaginary parts close to zero.
Reference
https://numpy.org/doc/stable/reference/generated/numpy.real_if_close.html