Skip to main content
v2026.11,858 entries · CC-BY 4.0

NumPy sqrt: np.sqrt() Syntax, Negatives and Arrays

np.sqrt takes element-wise square roots. See what it returns for negatives (nan, complex or ValueError) and how to use where= and out=.

Written and maintained by CASRAI Editorial Board

Last updated

numpy.sqrt returns the non-negative square root of an array, element by element. The call np.sqrt([1, 4, 9]) gives array([1., 2., 3.]), and a scalar input gives a scalar. The part that trips researchers up is the negative number: with real input np.sqrt returns nan (with a warning) instead of raising an error, while np.emath.sqrt returns a complex result and math.sqrt raises ValueError. This guide sets the behaviours side by side, then shows how to take square roots only where they are defined using where= and out=.

What np.sqrt is used for in research

Square roots appear wherever a variance-like quantity has to be put back on the scale of the data. A standard deviation is the square root of a variance, a root-mean-square error is the square root of a mean squared error, and a standard error of the mean is the standard deviation divided by the square root of the sample size. These are definitional formulas, and np.sqrt is the element-wise step in each. The Frobenius norm is also a square root, of a sum of squares; the numpy.linalg.norm guide covers that case, and the SEM guide shows the standard-error formula in a spreadsheet.

Install or access

np.sqrt ships with NumPy, so there is nothing separate to install. The official NumPy install page (numpy.org/install, checked 2026-10-29) gives pip install numpy, ideally inside a virtual environment created with python -m venv my-env and activated with source my-env/bin/activate on macOS and Linux or my-env\Scripts\activate on Windows. With conda it gives conda create -n my-env, conda activate my-env and conda install numpy. Check the install with:

import numpy as np
print(np.__version__)

Step-by-step: taking square roots with np.sqrt

The signature in the NumPy manual is numpy.sqrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True). Only x is needed for everyday use.

  1. Import NumPy. import numpy as np
  2. Pass a list, an array or a scalar. np.sqrt([1, 4, 9]) returns array([1., 2., 3.]). The manual describes x as array_like and states that the output has the same shape as the input, and is a scalar if the input is a scalar.
  3. Apply it to a column of data. np.sqrt(variances) turns an array of variances into an array of standard deviations in one call, with no loop.
  4. Write the result into an existing array if needed. out= names the location to store the result, and its shape must be one the inputs broadcast to.
  5. Restrict the calculation with where=. Where the condition is True the result is computed; elsewhere out keeps its value. This is the pattern for data that may contain negatives (see the next section).

Output and how to read it: nan, complex and inf

The manual states that if all elements are real, the result is real and negative elements return nan; if any element is complex, a complex array is returned and the square roots of negative reals are calculated. Its own example is np.sqrt([4, -1, np.inf]), which returns array([ 2., nan, inf]), so an infinite input stays infinite.

Negative inputs: four functions, four results

Call Input What happens Source
np.sqrt(-1.0) real float returns nan NumPy manual, numpy.sqrt
np.sqrt(-1+0j) complex complex result NumPy manual, numpy.sqrt
np.emath.sqrt(-1) real returns 1j NumPy manual, numpy.emath.sqrt
math.sqrt(-1.0) real raises ValueError Python docs, math module

The mixed-list trap

Because one complex element makes the whole result complex, a list that mixes types changes the output type of every entry. The manual’s example np.sqrt([4, -1, -3+4J]) returns array([2.+0.j, 0.+1.j, 1.+2.j]): the -1 becomes 0.+1.j and even the 4 comes back as 2.+0.j. An array that has been accidentally given a complex dtype will therefore never produce nan for negatives, which can hide a data-entry error.

Why emath results can differ in sign

The manual for numpy.emath.sqrt notes that floating-point 0.0 and -0.0 are distinct. Its examples show np.emath.sqrt(complex(-4.0, 0.0)) returning 2j and np.emath.sqrt(complex(-4.0, -0.0)) returning -2j. The manual for np.sqrt also records that the branch cut is the real interval [-inf, 0), continuous from above.

Worked pattern: square roots only where they are defined

This illustrative snippet computes square roots for the non-negative entries and leaves a chosen fill value (here 0.0) for the others, with no nan:

import numpy as np

x = np.array([4.0, -1.0, 9.0])
out = np.zeros_like(x)  # fill value for the skipped entries
np.sqrt(x, out=out, where=x >= 0)
print(out)  # [2. 0. 3.]

Supplying out matters. The manual says that with the default out=None, locations where the where condition is False remain uninitialized, so a bare np.sqrt(x, where=x >= 0) can return arbitrary values for the skipped entries. Whether replacing negatives with 0.0 is appropriate is a research decision: a negative variance usually signals a calculation problem that should be reported, not masked.

Troubleshooting

  • A nan appears in the output. A negative real value was passed. Locate it with np.isnan(result) (see NumPy NaN: detect, ignore and replace), then decide whether it is bad data or a case that needs complex output.
  • A warning says invalid value encountered in sqrt. NumPy emits a runtime warning when np.sqrt is given a negative real value. A warning is not an error, so the script keeps running with nan in the result.
  • The result is a complex array when you expected real numbers. At least one input element, or the dtype of the input, is complex. Check x.dtype.
  • You want complex roots for negative reals without changing the dtype. Use np.emath.sqrt, which the manual says returns a complex value for negative input elements.
  • You need an error instead of nan for negative numbers. math.sqrt raises ValueError for invalid operations such as sqrt(-1.0), according to the Python documentation, which describes this as the behaviour of the current CPython implementation.

Free alternatives

All of these are free and part of NumPy or the Python standard library.

Function Use it for Negative input Source
numpy.sqrt Element-wise roots of arrays and scalars nan for real input NumPy manual
numpy.emath.sqrt Roots where negative reals should become complex complex result NumPy manual
math.sqrt The square root of x ValueError Python docs
cmath functions Complex numbers; the math docs direct you here for complex input complex numbers are supported Python docs
math.isqrt(n) The integer square root of a non-negative integer (added in Python 3.8) defined for non-negative integers only Python docs

FAQ

What does np.sqrt return for a negative number?

For real input it returns nan. If the input is complex, it returns the complex square root. Use np.emath.sqrt to get a complex result from real negatives automatically.

What is the difference between np.sqrt and math.sqrt?

np.sqrt works element-wise on arrays and returns nan for negative reals. math.sqrt returns the square root of x and raises ValueError for invalid operations such as sqrt(-1.0).

Does np.sqrt work on a Python list?

Yes. The manual’s own example is np.sqrt([1, 4, 9]), which returns array([1., 2., 3.]).

How do I take the square root of only the non-negative values?

Pass where=x >= 0 together with a pre-filled out array, as in the worked pattern above.

How do I get a standard deviation from a variance with NumPy?

Apply np.sqrt to the variance, since a standard deviation is the square root of the variance.

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about NumPy sqrt: np.sqrt() Syntax, Negatives and Arrays

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →

Ask CASRAI · Regulatory Radar

Research-admin question? Get an answer that links its sources.

An AI assistant specialized in research administration. Every answer links its sources to check before you act. 2 questions free, no account. $29/month after.

  • Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.
  • Every answer numbers its sources and links each one, so you can check the source yourself.