Python Program to Find the Square Root – 2024

Hey guys, in this blog we will see a Python Program to Find the Square Root of int, float, and a complex number.

For the square root of complex numbers, we will be using the cmath library.

Example 1: Square root of an int

# Python Program to Find the Square Root

num = 8 

## lets calculate the square root
sqrt_of_num = num ** 0.5

print('Square root of %0.3f is %0.3f'%(num ,sqrt_of_num ))

Output

Square root of 8.000 is 2.828

Here we are simply doing (8)0.5 to find the square root of 8.

We can also take input from the user using input() and apply this operation to that variable to find that number’s square root.

Example 2: Square root of a float

# Python Program to Find the Square Root

num = 6.8

## lets calculate the square root
sqrt_of_num = num ** 0.5

print('Square root of %0.3f is %0.3f'%(num ,sqrt_of_num ))

Output

Square root of 6.800 is 2.608

Here we are simply doing (6.8)0.5 to find the square root of 6.8.

This is almost similar to the operation in Example 1 except for the fact that here we are applying the square root on a decimal/float number.

Example 3: Square root of a complex number

# Find square root of real or complex numbers
# Importing the complex math module
import cmath

complex_num = 4+6j

complex_num_sqrt = cmath.sqrt(complex_num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,complex_num_sqrt.real,complex_num_sqrt.imag))

Output

The square root of (1+2j) is 2.368+1.267j

Here we are calculating the square root of a complex number. A complex number is a special type of number which has two parts; a real part and an imaginary part.

Here we have used a special python library cmath to find the square root of our imaginary number.

Our result will be having two different parts complex_num_sqrt.real and complex_num_sqrt.imag which show the real part and imaginary part respectively.

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *