NumPy real_if_close()
The numpy.real_if_close()
function returns the real part of a complex-valued array if the imaginary components are close to zero. This is useful for simplifying computations where small numerical errors may introduce negligible imaginary parts.
Syntax
numpy.real_if_close(a, tol=100)
Parameters
Parameter | Type | Description |
---|---|---|
a | array_like | Input array containing real or complex numbers. |
tol | float, optional | Tolerance for treating the imaginary part as negligible. It is multiplied by the machine epsilon of the data type. |
Return Value
Returns an ndarray. If all imaginary parts of a
are within the defined tolerance, the function returns a real-valued array; otherwise, it keeps the complex values.
Examples
1. Converting a Complex Array with Small Imaginary Parts
Here, we check how real_if_close()
converts a complex array when the imaginary part is negligible.
import numpy as np
# Define a complex array with small imaginary parts
arr = np.array([1.0 + 1e-10j, 2.0 + 1e-12j, 3.0 + 1e-8j])
# Apply real_if_close function
result = np.real_if_close(arr)
# Print the result
print("Converted array:", result)
Output:
Converted array: [1. 2. 3.]
Since the imaginary parts are close to zero, the function returns a real-valued array.
2. Handling Large Imaginary Parts
If the imaginary part is significant, real_if_close()
does not remove it.
import numpy as np
# Define a complex array with larger imaginary parts
arr = np.array([1.0 + 1e-2j, 2.0 + 0.5j, 3.0 + 1e-3j])
# Apply real_if_close function
result = np.real_if_close(arr)
# Print the result
print("Converted array:", result)
Output:
Converted array: [1. +0.01j 2. +0.5j 3. +0.001j]
Since the imaginary parts are not sufficiently small, they remain in the output.
3. Adjusting the Tolerance Level
Changing the tolerance level can influence whether imaginary parts are considered negligible.
import numpy as np
# Define a complex array
arr = np.array([1.0 + 1e-6j, 2.0 + 1e-10j, 3.0 + 1e-3j])
# Apply real_if_close with different tolerance values
result_high_tol = np.real_if_close(arr, tol=1e6)
result_low_tol = np.real_if_close(arr, tol=1)
# Print the results
print("High tolerance (1e6):", result_high_tol)
print("Low tolerance (1):", result_low_tol)
Output:
High tolerance (1e6): [1. 2. 3.]
Low tolerance (1): [1. +1.e-06j 2. +1.e-10j 3. +1.e-03j]
With a high tolerance, all imaginary parts are ignored. With a lower tolerance, small imaginary parts remain.