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
Compute the square root of negative input with emath in Python
NumPy's emath.sqrt() function computes the square root of input values, handling negative numbers by returning complex values. Unlike the standard numpy.sqrt(), which raises an error for negative inputs, emath.sqrt() returns complex numbers for negative values.
Syntax
numpy.emath.sqrt(x)
Parameters:
- x ? Input array or scalar value
Returns: Square root of x. For negative values, returns complex numbers with imaginary components.
Example with Mixed Positive and Negative Values
Let's compute square roots for an array containing both positive and negative numbers ?
import numpy as np
# Creating a numpy array with positive and negative values
arr = np.array([1, -4, -9, 16, -25, 36])
# Display the array
print("Our Array:")
print(arr)
# Check array properties
print("\nDimensions:", arr.ndim)
print("Datatype:", arr.dtype)
print("Shape:", arr.shape)
# Compute square root using emath.sqrt()
result = np.emath.sqrt(arr)
print("\nSquare roots:")
print(result)
Our Array: [ 1 -4 -9 16 -25 36] Dimensions: 1 Datatype: int64 Shape: (6,) Square roots: [1.+0.j 0.+2.j 0.+3.j 4.+0.j 0.+5.j 6.+0.j]
Comparison with Regular numpy.sqrt()
The standard numpy.sqrt() function raises a warning and returns NaN for negative values, while emath.sqrt() handles them gracefully ?
import numpy as np
negative_values = np.array([-4, -9, -16])
# Using emath.sqrt() - handles negatives
emath_result = np.emath.sqrt(negative_values)
print("emath.sqrt() result:")
print(emath_result)
# The result shows complex numbers with imaginary components
print("\nReal parts:", emath_result.real)
print("Imaginary parts:", emath_result.imag)
emath.sqrt() result: [0.+2.j 0.+3.j 0.+4.j] Real parts: [0. 0. 0.] Imaginary parts: [2. 3. 4.]
Working with Complex Results
The complex results can be used in further mathematical operations ?
import numpy as np
# Computing square roots of negative numbers
values = np.array([-1, -4, -25])
sqrt_results = np.emath.sqrt(values)
print("Original values:", values)
print("Square roots:", sqrt_results)
# Verify by squaring the results
verification = sqrt_results ** 2
print("Verification (should equal original):", verification)
Original values: [ -1 -4 -25] Square roots: [0.+1.j 0.+2.j 0.+5.j] Verification (should equal original): [-1.+0.j -4.+0.j -25.+0.j]
Conclusion
Use numpy.emath.sqrt() when you need to compute square roots of arrays that may contain negative values. It returns complex numbers for negative inputs, making it suitable for mathematical computations that require handling of complex results.
