Python NumPy – Return real parts if input is complex with all imaginary parts close to zero
In this article, we will discuss how to return real parts if the input is complex with all imaginary parts close to zero in Python.
The numpy np.real_if_close() method is used to return the real parts if the input is a complex number with all imaginary parts close to zero. “Close to zero” is defined as tol * (machine epsilon of the type for a).
syntax: numpy.real_if_close(a, tol=100)
- a: array like object. input array.
- tot: Machine epsilons tolerance for the complex component of the array’s elements.
out: The type of an is utilized for the output if an is true. The returning type is float if has complex elements.
In this example, the NumPy package is imported. An array is created using numpy.array() method which contains complex numbers where the imaginary parts are near 0 and np.real_if_close() returns the real parts. The shape, datatype, and dimensions of the array can be found by .shape, .dtype, and .ndim attributes.
[ 1.+0.e+00j 2.+3.e-18j -3.+4.e-14j] Shape of the array is : (3,) The dimension of the array is : 1 Datatype of our Array is : complex128 [ 1. 2. -3.]
In this case, imaginary numbers are not close to zero so the same array is returned back.
[1.+5.j 3.-6.j] Shape of the array is : (2,) The dimension of the array is : 1 Datatype of our Array is : complex128 [1.+5.j 3.-6.j]