Developer Reference

Square Root in Python — math.sqrt, ** Operator, cmath, NumPy & Decimal

Reviewed by Mateo·Last updated October 2026

Quick answer: Use import math; math.sqrt(x) for the square root of a non-negative float. For integer inputs where you want an exact integer result, use int(x**0.5) or Python 3.8+ math.isqrt(x). For complex numbers, use import cmath; cmath.sqrt(x). For arrays, use numpy.sqrt(arr).

Method 1: math.sqrt() — The Standard Choice

The math.sqrt() function from Python's built-in math module is the go-to for computing square roots of non-negative real numbers. It always returns a float, even when the result is a whole number. It raises a ValueError for negative inputs (use cmath.sqrt() for those).

Python
import math

result = math.sqrt(25)
print(result)        # 5.0  (always a float)

print(math.sqrt(2))  # 1.4142135623730951
print(math.sqrt(0))  # 0.0

# Raises ValueError for negatives:
# math.sqrt(-1)  →  ValueError: math domain error

Why choose math.sqrt() over the ** operator? It is faster on CPython for scalar values because it calls the C runtime's sqrt() directly without the overhead of Python's general-purpose exponentiation. It also signals intent clearly — anyone reading the code knows immediately you're computing a square root, not a general power.

Method 2: The ** Exponentiation Operator

Any number raised to the power of 0.5 is its square root. The ** operator works on integers, floats, and — unlike math.sqrt() — negative numbers (returning a complex result automatically in Python 3).

Python
x = 144
print(x ** 0.5)        # 12.0

# Works with negative numbers (returns complex):
print((-4) ** 0.5)      # (1.2246467991473532e-16+2j)  ← floating-point noise!

# Also works as a fraction:
from fractions import Fraction
print(Fraction(1, 4) ** Fraction(1, 2))  # Fraction(1, 2)  ← exact!

Watch out for floating-point noise with negatives: (-4) ** 0.5 gives approximately 2j but with a tiny real component from floating-point rounding. Use cmath.sqrt(-4) to get a clean 2j.

Method 3: math.isqrt() — Integer Square Root (Python 3.8+)

Introduced in Python 3.8, math.isqrt(n) returns the integer square root — the largest integer k such that k² ≤ n. It works on arbitrarily large integers (Python's int has no size limit) and never uses floating-point, so there's no precision loss for very large numbers.

Python
import math

print(math.isqrt(25))   # 5   (exact perfect square)
print(math.isqrt(26))   # 5   (floor, not rounded)
print(math.isqrt(35))   # 5
print(math.isqrt(36))   # 6

# Handles huge integers exactly:
n = 10 ** 50
print(math.isqrt(n))    # 100000000000000000000000000 (exact)

This is the correct tool any time you need to check whether a number is a perfect square or work with integer arithmetic — for example, in competitive programming, number theory, or anywhere you'd otherwise do int(math.sqrt(n)) and worry about off-by-one errors from floating-point rounding.

Method 4: cmath.sqrt() — Complex Number Square Roots

The cmath module mirrors math but operates in the complex number plane. cmath.sqrt() never raises a ValueError — it returns a complex number for any real or complex input. This is the right tool when you're working with complex-valued computations, signal processing, or solving polynomial equations.

Python
import cmath

print(cmath.sqrt(25))    # (5+0j)
print(cmath.sqrt(-4))    # 2j  (clean, no floating-point noise)
print(cmath.sqrt(-1))    # 1j  (imaginary unit i)

# Complex input:
print(cmath.sqrt(3 + 4j)) # (2+1j)

Method 5: numpy.sqrt() — Arrays and Vectorized Operations

When you're working with a list or array of numbers, looping over them and calling math.sqrt() on each is slow. NumPy's numpy.sqrt() applies the square root element-wise across an entire array in compiled C, which is typically 10–100× faster for large datasets.

Python
import numpy as np

arr = np.array([1, 4, 9, 16, 25])
print(np.sqrt(arr))
# [1. 2. 3. 4. 5.]

# 2D arrays work too:
matrix = np.array([[4, 9], [16, 25]])
print(np.sqrt(matrix))
# [[2. 3.]
#  [4. 5.]]

# NaN for negative elements (no error by default):
print(np.sqrt(np.array([4, -1, 9])))
# [ 2. nan  3.]  + RuntimeWarning

Method 6: decimal.Decimal — Arbitrary Precision

Both math.sqrt() and float ** 0.5 use 64-bit IEEE 754 floating-point, giving you about 15–17 significant digits. If you need more precision — say, computing √2 to 50 decimal places — use Python's decimal module with a custom precision context.

Python
from decimal import Decimal, getcontext

getcontext().prec = 50  # 50 significant figures

result = Decimal(2).sqrt()
print(result)
# 1.4142135623730950488016887242096980785696718753769

# Compare to float:
import math
print(math.sqrt(2))
# 1.4142135623730951  (only 16 digits)

Comparing All Methods

MethodReturnsNegativesBest for
math.sqrt(x)floatValueErrorGeneral scalar use
x ** 0.5float / complexComplex resultQuick inline, fractions
math.isqrt(x)intValueErrorInteger arithmetic, perfect square check
cmath.sqrt(x)complexcomplexComplex numbers, signal processing
numpy.sqrt(arr)ndarraynan + warningArrays, data science, machine learning
Decimal.sqrt()DecimalInvalidOperationHigh-precision arithmetic

Checking for Perfect Squares

A common pattern is testing whether an integer is a perfect square. The cleanest Python 3.8+ approach uses math.isqrt():

Python
import math

def is_perfect_square(n: int) -> bool:
    if n < 0:
        return False
    root = math.isqrt(n)
    return root * root == n

print(is_perfect_square(25))   # True
print(is_perfect_square(26))   # False
print(is_perfect_square(0))    # True
print(is_perfect_square(10**20 + 1))  # False (huge int, still exact)

Why not int(math.sqrt(n)) ** 2 == n? For large integers (above ~2⁵³), math.sqrt() loses precision and may round the integer root up or down, giving wrong results. math.isqrt() is exact for any size integer.

Printing the √ Symbol in Python

If you want to display the actual square root symbol in output strings, use the Unicode escape √ or paste the character directly — Python 3 source files default to UTF-8.

Python
symbol = "√"            # Unicode escape
print(f"{symbol}25 = 5")   # √25 = 5

# Or paste directly (UTF-8 source):
print(f"√{n} = {math.sqrt(n):.4f}")

# ord() and chr() confirm the codepoint:
print(ord("√"))   # 8730
print(chr(8730))  # √

Frequently Asked Questions

What is the difference between math.sqrt() and ** 0.5 in Python?

math.sqrt(x) always returns a float and raises ValueError for negative inputs. x ** 0.5 also returns a float for positive values, but returns a complex number for negative integers instead of raising an error. For scalar values, math.sqrt() is slightly faster because it calls the C runtime's sqrt() directly. For fractions or symbolic computation, ** with Fraction or sympy can return exact results.

How do I get the square root of a negative number in Python?

Use cmath.sqrt(): import cmath; cmath.sqrt(-4) returns 2j. Avoid (-4) ** 0.5 — it also returns a complex number but often includes a tiny non-zero real part from floating-point rounding (e.g., 1.2e-16+2j instead of a clean 2j).

How do I calculate the square root of every element in a list?

Three options, from simplest to fastest: (1) list comprehension: [math.sqrt(x) for x in lst]; (2) map(): list(map(math.sqrt, lst)); (3) NumPy: numpy.sqrt(numpy.array(lst)). For large lists (thousands of elements or more), NumPy is typically 50–100× faster than a Python loop.

How do I check if a number is a perfect square in Python?

Use math.isqrt() (Python 3.8+): root = math.isqrt(n); return root * root == n. This is exact for arbitrarily large integers. Do not use int(math.sqrt(n)) ** 2 == n — for integers larger than 2⁵³, floating-point rounding in math.sqrt() can return the wrong integer root.

How do I get more decimal places for a square root in Python?

Use Python's decimal module with a custom precision context: from decimal import Decimal, getcontext; getcontext().prec = 50; Decimal(2).sqrt(). This gives you 50 significant figures. The mpmath library is another option and can go even higher with mpmath.mp.dps = 100 for 100 decimal places.