Square root of a negative number in Python

Use of complex numbers help us get the square root of a negative number in Python. In complex numbers, we have an imaginary unit (i.e. i). In Python it is denoted by j. And, defined as –

imaginary unit j square

Use the cmath module to get the square root of a negative number. The module has various mathematical functions for complex numbers. This is different from the math module – which doesn’t support complex numbers. We will also look at the response from the interpreter while using math module functions on complex numbers later. For now –

Square root of a negative number in Python using cmath module

As already discussed, cmath module has the support for complex numbers. There is a sqrt() function in cmath module through which we can get the required outcome.

First, open the Python shell and then import cmath module –

>>> import cmath

next, use sqrt() function

>>> cmath.sqrt(x)

where, x is a negative number.

For instance, if we wish to get the square root of -9

>>> import cmath
>>> cmath.sqrt(-9)

The response we get from the interpreter –

3j

Additional Info –

Lets see what happens in case we try to find the square root of a negative number (-9) using a math module.

>>> import math
>>> math.sqrt(-9)

The response will be –

ValueError: math domain error

It clearly states that we can’t use mathematical functions in math module for complex numbers.

Word of Caution –

Since, both modules have same function names for finding the square root i.e. sqrt(). In case we are working with both the modules i.e. math and cmath in our program. Then, to avoid an inadvertent error – we should clearly state the sqrt() function with module name.

Consider a scenario where we import both the modules. Then, the interpreter would import the function sqrt() from the module which was imported last. For instance –

>>> from math import sqrt
>>> from cmath import sqrt

Now, if we will do sqrt(9) – it would get us the response –

(3+0j)

Although we intend to use the math module, but it was cmath which was imported last. Therefore, we got response from sqrt() function from cmath module. So, it is always better to specifically state the module we are about to use for a function.

In conclusion, we have discussed how to get the square root of a negative number in Python using cmath module. We also touched upon the confusion which may creep in while using math & cmath module.

Similar Posts