PythonMastery

Square root in Python

Find a square root with ** 0.5, math.sqrt() and math.isqrt(), handle negative numbers, and calculate one by hand with Newton's method.

There are three common ways to get a square root in Python. All three are short, but they give different types of result.

The program

python
import math

n = 144

print(n ** 0.5)
print(math.sqrt(n))
print(math.isqrt(n))
print(math.isqrt(150))
print(2 ** 0.5)
output
12.0
12.0
12
12
1.4142135623730951

How it works

Negative numbers

A negative number has no real square root. math.sqrt(-4) raises ValueError: math domain error. The cmath module works with complex numbers and does give an answer:

python
import cmath

print(cmath.sqrt(-4))
output
2j

j is how Python writes the imaginary unit i (the square root of -1). If you do not need complex numbers, check if n < 0: before calling math.sqrt().

By hand: Newton's method

Without any library, you can start with a guess and improve it. Each new guess is the average of the guess and n / guess:

python
n = 2
guess = n / 2

for step in range(1, 6):
    guess = (guess + n / guess) / 2
    print(step, guess)
output
1 1.5
2 1.4166666666666665
3 1.4142156862745097
4 1.4142135623746899
5 1.414213562373095

If the guess is too big, n / guess is too small, so their average is closer to the real root. The number of correct digits roughly doubles at each step. After 5 steps, every digit matches 2 ** 0.5 except the last one. That small difference comes from rounding in float arithmetic.

Learn the idea: Numbers in Depth: Integers, Floats, and the math Module, Modules & Imports