askvity

How do you square root a complex number in Python?

Published in Complex Number Operations 2 mins read

You can calculate the square root of a complex number in Python using the cmath.sqrt() method.

Using the cmath.sqrt() Method

The cmath module in Python provides functions for working with complex numbers. The sqrt() function within this module specifically calculates the square root of a complex number.

Here's how to use it:

import cmath

complex_number = 1 + 2j
square_root = cmath.sqrt(complex_number)

print(square_root)

In this example:

  1. We import the cmath module.
  2. We define a complex number complex_number.
  3. We use cmath.sqrt() to calculate its square root and store it in the square_root variable.
  4. Finally, we print the result.

Important Note: According to the reference, the input to the cmath.sqrt() function must be greater than or equal to 0. However, this constraint refers to the function’s intended use with real numbers within the math module (which throws a ValueError for negative inputs). The cmath.sqrt() function is specifically designed to handle complex numbers, including those with negative real components.

Example with a negative real part:

import cmath

complex_number = -1 + 0j # Representing the real number -1 as a complex number
square_root = cmath.sqrt(complex_number)
print(square_root) # Output: 0.0+1.0j

Summary Table

Function Description Module Input Type Output Type
cmath.sqrt() Calculates the square root of a number. cmath Complex number Complex number

Related Articles