np.sqrt() applies element-wise, and for a real-valued input array, it produces nan, with a RuntimeWarning, for any negative element, since a negative number has no real square root — NumPy doesn't automatically upgrade the result to complex. If you know an array might contain values with a meaningful negative square root, you'd first convert it to a complex dtype, since np.sqrt() on a complex-typed array does correctly compute complex results.
1Understanding np.sqrt()
np.sqrt() applies element-wise, and for a real-valued input array, it produces nan, with a RuntimeWarning, for any negative element, since a negative number has no real square root — NumPy doesn't automatically upgrade the result to complex. If you know an array might contain values with a meaningful negative square root, you'd first convert it to a complex dtype, since np.sqrt() on a complex-typed array does correctly compute complex results.
np.sqrt() on a real array with negative values silently produces nan for those positions plus a warning, rather than raising an error — check for negative values first, or cast to a complex dtype explicitly, if that's a real possibility in your data.
import numpy as np
arr = np.array([1, 4, 9, 16])
print(np.sqrt(arr))2Practical Example
Here is a real-world application of np.sqrt() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([4, -1, 9])
print(np.sqrt(arr))3Best Practices
Follow these guidelines when working with np.sqrt():
1. Check for negative values before calling np.sqrt() on real-valued data if negatives are a realistic possibility, to avoid silent nan results
2. Cast the array to a complex dtype explicitly if you specifically need complex square roots of negative values
3. Prefer np.sqrt(x) over x ** 0.5 for clarity, since it directly names the mathematical operation being performed
Tip: np.sqrt() on a real array with negative values silently produces nan for those positions plus a warning, rather than raising an error — check for negative values first, or cast to a complex dtype explicitly, if that's a real possibility in your data.
import numpy as np
arr = np.array([1, 4, 9, 16])
print(np.sqrt(arr))