Python Language Exponentiation Square root: math.sqrt() and cmath.sqrt


The math module contains the math.sqrt()-function that can compute the square root of any number (that can be converted to a float) and the result will always be a float:

import math

math.sqrt(9)                # 3.0
math.sqrt(11.11)            # 3.3331666624997918
math.sqrt(Decimal('6.25'))  # 2.5

The math.sqrt() function raises a ValueError if the result would be complex:


ValueError: math domain error

math.sqrt(x) is faster than math.pow(x, 0.5) or x ** 0.5 but the precision of the results is the same. The cmath module is extremely similar to the math module, except for the fact it can compute complex numbers and all of its results are in the form of a + bi. It can also use .sqrt():

import cmath

cmath.sqrt(4)  # 2+0j
cmath.sqrt(-4) # 2j

What's with the j? j is the equivalent to the square root of -1. All numbers can be put into the form a + bi, or in this case, a + bj. a is the real part of the number like the 2 in 2+0j. Since it has no imaginary part, b is 0. b represents part of the imaginary part of the number like the 2 in 2j. Since there is no real part in this, 2j can also be written as 0 + 2j.