To get the square root in Python, import math and call math.sqrt(x), which returns a float: math.sqrt(16) gives 4.0. For an exact integer result use math.isqrt(n), and for negative numbers use cmath.sqrt(x).
Square root in Python with math.sqrt()
math.sqrt(x) is documented as "Return the square root of x". It accepts an int or a float and always returns a float.
import math
print(math.sqrt(16))
print(math.sqrt(2))
print(math.sqrt(0.25))
Example output:
4.0
1.4142135623730951
0.5
The result of math.sqrt(2) is the closest float to the true value, not the exact value, because the square root of 2 is irrational and a float has a fixed number of bits. Even math.sqrt(16) prints 4.0 rather than 4. If you need an int, see math.isqrt() below.
Square root with the ** operator
A square root is the same as raising to the power 0.5, so this works without an import:
print(16 ** 0.5)
print(pow(16, 0.5))
Example output:
4.0
4.0
The Python docs state that the two-argument pow(base, exp) is equivalent to base**exp. For positive numbers, ** and math.sqrt give the same kind of answer. The practical differences are readability (math.sqrt(x) says what it does) and what happens with negative input, covered next. The docs also point out that math.pow() converts both arguments to float, unlike the built-in **, which is why math.pow is not a good choice for exact integer powers.
Square root of a negative number in Python
The three tools behave differently when the input is below zero:
| Call | Result for -4 |
|---|---|
math.sqrt(-4) | Raises ValueError |
(-4) ** 0.5 | A complex number close to 2j |
cmath.sqrt(-4) | The complex number 2j |
The math docs say the implementation raises ValueError for invalid operations such as sqrt(-1.0). The usual message is:
ValueError: math domain error
That line is example output; the docs name the exception type, not the message text. The built-in pow() documentation says that for a negative int or float base and a non-integral exponent "a complex result is delivered", and gives pow(-9, 0.5) returning a value close to 3j. "Close to" matters: the real part is a tiny nonzero number from floating-point arithmetic, not exactly 0.
When you want a clean complex answer, use the cmath module. Its functions always return a complex number, even when the answer is real:
import cmath
print(cmath.sqrt(-4))
print(cmath.sqrt(4))
print(cmath.sqrt(-2-0j))
print(cmath.sqrt(-2+0j))
Example output:
2j
(2+0j)
-1.4142135623730951j
1.4142135623730951j
The last two lines come from the cmath documentation. They show that cmath.sqrt has a branch cut along the negative real axis, and the sign of the zero imaginary part decides which side of the cut a negative real number is treated as being on. For ordinary cmath.sqrt(-4) you get the positive imaginary root.
If you just want to guard against bad input instead of getting complex numbers, check first:
import math
def safe_sqrt(value: float) -> float:
if value < 0:
raise ValueError(f"cannot take the real square root of {value}")
return math.sqrt(value)
Integer square root with math.isqrt()
math.isqrt(n) was added in Python 3.8. Its documentation: "Return the integer square root of the nonnegative integer n. This is the floor of the exact square root of n." It returns an int, and it never goes through a float, so it is exact for huge integers.
from math import isqrt
print(isqrt(16))
print(isqrt(10))
print(isqrt(10**40))
Example output:
4
3
100000000000000000000
isqrt(10) is 3 because 3 squared is 9, which is at most 10, while 4 squared is 16. The result is rounded down, never to the nearest integer. If you need the ceiling instead, the docs give the formula 1 + isqrt(n - 1) for positive n.
Here is why this matters. Take a number slightly above 1020 and square it:
import math
n = 10**20 + 1
square = n * n
print(math.isqrt(square) == n)
print(math.sqrt(square) == n)
Example output:
True
False
math.sqrt converts its argument to a float first. Floats near 1020 are spaced thousands of units apart, so the extra + 1 disappears and the result is 1e+20, which does not equal n. isqrt keeps full integer precision and returns n exactly.
Check if a number is a perfect square
Use isqrt, then square the result and compare. This avoids float rounding entirely:
from math import isqrt
def is_perfect_square(n: int) -> bool:
if n < 0:
return False
root = isqrt(n)
return root * root == n
print(is_perfect_square(144))
print(is_perfect_square(145))
Example output:
True
False
The same idea is used for primality tests, where you only need to try divisors up to the integer square root. See how to check if a number is prime in Python for a full example.
Cube roots and other roots
From Python 3.11, math.cbrt(x) returns the cube root. For other roots, use a fractional exponent:
import math
print(math.cbrt(27))
print(32 ** (1 / 5))
Example output:
3.0
2.0
Expect small floating-point error on some inputs, since 1/5 cannot be stored exactly. If the last digits matter, compare with math.isclose() instead of ==.
A related need is the distance between two points. math.hypot(x, y) computes sqrt(x*x + y*y), and since Python 3.8 it accepts more than two coordinates. The docs note it is more accurate than writing the square root yourself, with a maximum error under 1 ulp from Python 3.10:
import math
print(math.hypot(3, 4))
Example output:
5.0
Square root of every item in a list or array
math.sqrt works on one number at a time. For a list, use a list comprehension:
import math
numbers = [1, 4, 9, 16]
roots = [math.sqrt(number) for number in numbers]
print(roots)
Example output:
[1.0, 2.0, 3.0, 4.0]
If you already use NumPy, numpy.sqrt works element by element on a whole array. Its docs show np.sqrt([1, 4, 9]) returning array([1., 2., 3.]). NumPy treats negative real input differently from the standard library: the docs say negative elements return nan for all-real input, rather than raising an error. Its docs also show that if any element is complex, the whole result becomes complex. Because of this, check your data for negative values before relying on the output.
For a list comprehension primer, see Python list comprehension.
Which one should you use?
- A float result from a nonnegative number:
math.sqrt(x). - An exact integer result, or very large integers:
math.isqrt(n). - Negative numbers where a complex answer is correct:
cmath.sqrt(x). - Whole arrays of numbers:
numpy.sqrt(array). - A quick one-off with no import:
x ** 0.5, as long as you are happy to get a complex number for negativex.
If you get an error
NameError: name 'sqrt' is not defined means you called sqrt(16) without importing it. Either write math.sqrt(16) after import math, or use from math import sqrt. ValueError: math domain error means the input was negative; use cmath.sqrt or validate first, as shown above. If you see TypeError, check that you passed a number and not a string, for example the raw result of input(), which must be converted with float() first.
Frequently asked questions
- What is the difference between math.sqrt and math.isqrt?
- math.sqrt(x) returns a float that approximates the square root. math.isqrt(n) takes a nonnegative integer and returns the floor of its exact square root as an int, so it stays exact for integers of any size. For example, isqrt(10) is 3.
- How do I take the square root of a negative number in Python?
- Use cmath.sqrt, which returns a complex number: cmath.sqrt(-4) gives 2j. math.sqrt(-4) raises ValueError, and (-4) ** 0.5 returns a complex number close to 2j, with a tiny floating-point error in the real part.
- How do I take a cube root or other root in Python?
- From Python 3.11, math.cbrt(x) returns the cube root. For any other root, raise to a fractional power, for example 32 ** (1/5), and expect a small floating-point error because 1/5 is not stored exactly.
- How do I check whether a number is a perfect square?
- For a nonnegative integer n, compute root = math.isqrt(n) and test root * root == n. Avoid comparing math.sqrt(n) with its own int() value for large n, because the float loses precision.