Python Square Root of a Number With Examples

There are many ways to find the square root of a number in Python.

  • Exponent Operator
  • Math.sqrt() function
  • Math.pow() function

1. Using Exponent Operator for Square Root of a Number


num = input("Please enter a number:n")
sqrt = float(num) ** 0.5
print(f'{num} square root is {sqrt}')

Output:


Please enter a number:
4.344
4.344 square root is 2.0842264752180846
Please enter a number:
10
10 square root is 3.1622776601683795

I am using float() built-in function to convert the user-entered string to a floating-point number.

The input() function is used to get the user input from the standard input.

2. Math sqrt() function for square root

Python math module sqrt() function is the recommended approach to get the square root of a number.


import math
num = 10
num_sqrt = math.sqrt(num)
print(f'{num} square root is {num_sqrt}')

Output:

Python Square Root of a Number

 

Python Square Root Of Number

3. Math pow() function for square root

It’s not a recommended approach. But, the square root of a number is the same as the power of 0.5.


>>> import math
>>>
>>> math.pow(10, 0.5)
3.1622776601683795
>>>

4. Square Root of Complex Number

We can use cmath module to get the square root of a complex number.


import cmath
c = 1 + 2j
c_sqrt = cmath.sqrt(c)
print(f'{c} square root is {c_sqrt}')

Output:


(1+2j) square root is (1.272019649514069+0.7861513777574233j)

5. Square Root of a Matrix / Multidimensional Array

We can use NumPy sqrt() function to get the square root of a matrix elements.

By admin

Leave a Reply

%d bloggers like this: