Sunday, November 17, 2024
Google search engine
HomeLanguagesPython NumPy – Return real parts if input is complex with all...

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)

parameters:

  • a: array like object. input array.
  • tot: Machine epsilons tolerance for the complex component of the array’s elements.

returns:

out: The type of an is utilized for the output if an is true. The returning type is float if has complex elements.

Example 1:

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.

Python3




import numpy as np
  
# Creating an array
array = np.array([1,2+3.e-18j,-3+4.e-14j])
print(array)
  
# shape of the array is
print("Shape of the array is : ",array.shape)
  
# dimension of the array
print("The dimension of the array is : ",array.ndim)
  
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
  
# returning real part
print(np.real_if_close(array, tol= 1000))


Output:

[ 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.]

Example 2:

In this case, imaginary numbers are not close to zero so the same array is returned back.

Python3




import numpy as np
  
# Creating an array
array = np.array([1+5j,3-6j])
print(array)
  
# shape of the array is
print("Shape of the array is : ",array.shape)
  
# dimension of the array
print("The dimension of the array is : ",array.ndim)
  
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
  
# returning real part
print(np.real_if_close(array, tol= 1000))


Output:

[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]

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments