Square root math.sqrt and cmath.sqrt
suggest changeThe 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
from decimal import Decimal
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:
math.sqrt(-10)
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 imaginary unit, the square root of -1. Python writes a complex value as a + bj. a is the real part, as in the 2 of 2+0j. b is the imaginary coefficient, as in the 2 of 2j, which is the same value as 0 + 2j.