Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Return real parts if input is complex with all imaginary parts close to zero in Python
The numpy.real_if_close() function returns the real parts of a complex array when the imaginary parts are close to zero. "Close to zero" is defined as tol * machine_epsilon, where tol is the tolerance parameter.
Syntax
numpy.real_if_close(a, tol=100)
Parameters
The function accepts the following parameters ?
- a ? Input array (complex or real)
- tol ? Tolerance in machine epsilons (default: 100)
Example
Let's see how to extract real parts when imaginary parts are negligible ?
import numpy as np
# Creating a complex array with very small imaginary parts
arr = np.array([2.1 + 4e-14j, 5.2 + 3e-15j])
# Display the array
print("Our Array...")
print(arr)
# Check array properties
print("\nDimensions:", arr.ndim)
print("Datatype:", arr.dtype)
print("Shape:", arr.shape)
# Extract real parts if imaginary parts are close to zero
result = np.real_if_close(arr, tol=1000)
print("\nResult...")
print(result)
print("Result datatype:", result.dtype)
Our Array... [2.1+4.e-14j 5.2+3.e-15j] Dimensions: 1 Datatype: complex128 Shape: (2,) Result... [2.1 5.2] Result datatype: float64
Different Tolerance Values
The tolerance parameter determines how close to zero the imaginary parts must be ?
import numpy as np
# Array with larger imaginary parts
arr = np.array([3.0 + 1e-10j, 4.0 + 1e-12j])
print("Original array:")
print(arr)
# With low tolerance - keeps complex
print("\nWith tol=100:")
print(np.real_if_close(arr, tol=100))
# With high tolerance - returns real
print("\nWith tol=1000000:")
print(np.real_if_close(arr, tol=1000000))
Original array: [3.+1.e-10j 4.+1.e-12j] With tol=100: [3.+1.e-10j 4.+1.e-12j] With tol=1000000: [3. 4.]
Real Input Arrays
When the input is already real, the function returns the same array ?
import numpy as np
# Real array
real_arr = np.array([1.5, 2.7, 3.9])
print("Real array:")
print(real_arr)
result = np.real_if_close(real_arr)
print("\nResult:")
print(result)
print("Same object?", real_arr is result)
Real array: [1.5 2.7 3.9] Result: [1.5 2.7 3.9] Same object? True
Conclusion
Use numpy.real_if_close() to extract real parts from complex arrays when imaginary components are negligible. Adjust the tolerance parameter to control the sensitivity of the "close to zero" condition.
Advertisements
