How to Find Square Root of a Real or Complex Number in Python?
Yo fam! We gonna learn the way to find the square root of a real or a complex number in Python. We shall use import, data types, and operators in Python. Precisely speaking, we use sqrt() function in the cmath.
Published in
2 min readJan 30, 2019
The square root of a number is a value that, when multiplied by itself, gives the number. In 3 x 3 = 9
, 3
is a square root of 9
. Also, note that (-3) x (-3)
also equals to 9
. Hence -3
is also a square root of 9
. But, ‘√’ always denotes a positive square root such as √16 is always equal to +4
.
Python Code
# Find square root of real or complex numbers
# Import the complex math module
import cmath# change this value for a different result
num = 13+3j# uncommment to take input from the user
#num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))
Output
The square root of (13+3j) is 3.629+0.413j
Explanation
For finding the square root of a positive real number, we can use the **
otherwise called, exponent operator as mentioned here, but for negative or complex numbers, we have to use the sqrt()
function in the cmath or the complex math module. Also, notice that we to use eval()
function instead of float()
to convert complex numbers as well.