Python Glossary Русский

all Python 3cmathfunction

cmath.sqrt()

powers and logarithms

Square root for complex numbers: unlike math.sqrt, the root of a negative number does not fail but gives an imaginary number.

Syntax

cmath.sqrt(z)

math.sqrt(-1) raises ValueError, while cmath.sqrt(-1) returns 1j. The price is that the result is always complex, even for 4: you get (2+0j), not 2.0, and such a number cannot be compared with < or passed to range. If you need a real root, use math.sqrt; reach for the complex answer only where it is really expected (roots of a quadratic with a negative discriminant). The sign of a zero imaginary part picks the branch: sqrt(complex(-4, -0.0)) gives -2j.

Examples

import cmath
import math
print(cmath.sqrt(-1))  # → 1j
print(cmath.sqrt(4))  # → (2+0j) — всегда complex
try:
    math.sqrt(-1)
except ValueError as e:
    print(type(e).__name__)  # → ValueError
import cmath
a, b, c = 1, 2, 5
d = cmath.sqrt(b * b - 4 * a * c)
print((-b + d) / (2 * a), (-b - d) / (2 * a))  # → (-1+2j) (-1-2j)
import cmath
print(cmath.sqrt(complex(-4, 0.0)), cmath.sqrt(complex(-4, -0.0)))  # → 2j -2j

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy