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 input with emath in Python
The numpy.emath.sqrt() function computes the square root of input values, returning complex numbers for negative inputs instead of raising errors. This function is part of NumPy's mathematical functions with automatic domain handling.
Syntax
numpy.emath.sqrt(x)
Parameters:
- x − Input value (scalar or array-like). Can be positive, negative, or complex numbers.
Returns: Square root of x. For negative inputs, returns complex numbers.
Basic Example with Positive Numbers
Let's compute square roots of positive numbers ?
import numpy as np
# Creating a numpy array with positive numbers
arr = np.array([1, 4, 9, 16, 25, 36])
print("Original Array:", arr)
print("Square roots:", np.emath.sqrt(arr))
Original Array: [ 1 4 9 16 25 36] Square roots: [1. 2. 3. 4. 5. 6.]
Handling Negative Numbers
Unlike numpy.sqrt(), emath.sqrt() handles negative numbers by returning complex results ?
import numpy as np
# Array with negative numbers
arr = np.array([-4, -9, 4, 9])
print("Original Array:", arr)
print("Square roots:", np.emath.sqrt(arr))
Original Array: [-4 -9 4 9] Square roots: [0.+2.j 0.+3.j 2.+0.j 3.+0.j]
Working with Scalar Values
The function works with both scalars and arrays ?
import numpy as np
# Scalar inputs
positive_scalar = 16
negative_scalar = -16
print("Square root of 16:", np.emath.sqrt(positive_scalar))
print("Square root of -16:", np.emath.sqrt(negative_scalar))
Square root of 16: 4.0 Square root of -16: 4j
Comparison with numpy.sqrt()
| Function | Positive Input | Negative Input | Error Handling |
|---|---|---|---|
numpy.sqrt() |
Real result | NaN + Warning | Runtime warning |
numpy.emath.sqrt() |
Real result | Complex result | No error |
Mixed Data Types
The function automatically handles different data types ?
import numpy as np
# Mixed positive and negative values
mixed_arr = np.array([0, 1, -1, 4, -4, 9, -9])
print("Original Array:", mixed_arr)
print("Square roots:", np.emath.sqrt(mixed_arr))
print("Result dtype:", np.emath.sqrt(mixed_arr).dtype)
Original Array: [ 0 1 -1 4 -4 9 -9] Square roots: [0.+0.j 1.+0.j 0.+1.j 2.+0.j 0.+2.j 3.+0.j 0.+3.j] Result dtype: complex128
Conclusion
Use numpy.emath.sqrt() when you need robust square root computation that handles negative inputs gracefully by returning complex numbers. This function is ideal for mathematical computations where domain errors should be avoided.
