How to Calculate Square Root in Python

In layman language square root can be defined as A square root of a number is a value that, when multiplied by itself, gives the number. In Python or any other Programming Language to calculate the square root of a number, we have different methods. And In this tutorial, we will try to cover all the methods to calculate the square root of a number.

To calculate the Square Root in Python we have basically 5 methods or ways. The most common or easiest way is by using a math module sqrt function. Python sqrt function is inbuilt in a math module, you have to import the math package (module). The sqrt function in the python programming language that returns the square root of any number (number > 0).

Different Ways to Calculate Square Root in Python

Generally, we have ways to calculate the square root in Python which are mentioned below:

  1. Using math.sqrt() Method
  2. Using ** operator
  3. For real or complex numbers using cmath module
  4. Using loop
  5. Python Square root of a Number using pow()

Calculating Square Root in Python Using sqrt() Function

Python math module deals with mathematical functions and calculations. Function sqrt() in the math module is used to calculate the square root of a given number. 

Syntax

Following is the syntax for Python sqrt() function.

import math
math.sqrt(num)

Parameters

num –  Here num can be any positive number whom square root you want.

Return Value of sqrt() Function

sqrt() method in Python will return the square root of the given number in floating-point. If the value is less than 0 then it will return Runtime Error.

Python sqrt() Function Compatibility

Python 2.xYes
Python 3.xYes

Examples Calculating Square Root Using sqrt() Function

Let’s see some examples to calculate the Python Square Root using sqrt() function.

Example 1: Calculating Square Root of a Positive Integer

import math
print("The square root of 25 is",math.sqrt(64))

Output:

The square root of 25 is 8.0
Calculating Python Square Root of a Positive Integer

Example 2: Calculating Square Root of a Floating Point Number

import math
print("The square root of 9.9 is:", math.sqrt(12.9))

Output:

The square root of 9.9 is: 3.591656999213594

Example 3: Calculating Square Root of 0

import math
print("The square root of 0 is",math.sqrt(0))

Output:

The square root of 0 is 0.0

Example 4: Calculating Square Root of a Negative Number

import math
print("The square root of -16 is",math.sqrt(-16))

Output:

Traceback (most recent call last):
  File "c:/Users/Karan/Desktop/test.py", line 2, in <module>
    print("The square root of -16 is",math.sqrt(-16))
ValueError: math domain error

So, when x<0 it does not execute instead generates a ValueError.

Example 5: Calculating Square Root of Boltzmann Constant

import math
# Find square root of boltzmann constant

boltzmannConstant_SqRoot = 1.38064852*pow(10,-23)

print("Square root of Boltzmann constant:{}".format(math.sqrt(boltzmannConstant_SqRoot)))

Output:

Square root of Boltzmann constant:3.715707900252655e-12

Notes:

  • math.sqrt() function is an inbuilt function in Python programming language that provides the square root of a given number.
  • In order to work math.sqrt() function you need to import “math” module (library).
  • If you pass the negative value in sqrt function, then python throws an error

Calculating Square Root in Python Using ** Operator

 ** operator is exponent operator. a**b (a raised to the power b).

Steps to Find Square Root in Python Using ** Operator

  1. Define a function named sqrt(n)
  2. Equation, n**0.5 is finding the square root and the result is stored in the variable x.
  3. Take input from the user and store in variable n.
  4.  The function is called to implement the action and print the result.
  5. Exit  

Example 1: Calculating Square Root of a Number Using ** Operator

def sqrt(n):
  if n < 0:
    return
  else:
    return n**0.5
  
print(sqrt(61))

Output:

7.810249675906654

Calculating Square Root in Python Using cmath Module

The cmath module is used to calculate the square root in python of Real or Complex number.

The above two methods will work fine for all positive real numbers. But for negative or complex numbers, it can be done as follows.

Example: Calculating Square Root of a Number Using cmath

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

# change this value for a different result
num = 1+2j

# 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 (1+2j) is 1.272+0.786j

In this program, we use the sqrt() function in the cmath (complex math) module. Notice that we have used the eval() function instead of float() to convert complex number as well. Also, notice the way in which the output is formatted. 

Calculating Square Root in Python Using Loop

Example:

num = int(input(" Please Enter any Postive Integer : "))
epont = int(input(" Enter Exponent Value to the power raise to : "))
power = 1
for loop in range(1, epont + 1):
 power = power * num
print("The Result of {0} Power {1} = {2}".format(num, epont, power))

Output:

Please Enter any Postive Integer : 5
Enter Exponent Value to the power raise to : 3
The Result of 5 Power 3 = 125

Calculating Square Root Using pow()

In this section, we are going to use the pow() built-in method to calculate the square root in Python.

Let us understand how does pow() function work in Python.

The pow() method takes 2 parameters, the first parameter is the numerical value, and the second parameter is the power of the numerical value. If we have a look at it, then you’ll notice that it is similar the way we have calculated the square root in the above examples.

The pow() method takes 2 parameters, the first parameter is the numerical value, and the second parameter is the power of the numerical value. If we have a look at it, then you’ll notice that it is similar the way we have calculated the square root in the above examples.

Syntax

pow(x,y)  # where y is the power of x or x**y 

Example: Calculating Square Root of a Number Using pow()

# Python Square root program
import math
number = float(input(" Please Enter any numeric Value : "))

squareRoot = math.pow(number, 0.5)

print("The Square Root of a Given Number {0}  = {1}".format(number, squareRoot))

Output:

Please Enter any numeric Value: 69
The Square Root of a Given Number 69.0  = 8.306623862918075

pow() is also a predefined method to find out the power of a number, it takes two arguments as input, first is the number itself and the second one is the power of that number. The program is same as the first program where we’re using (**) sign to find out the square root but the only difference is this that here we’re using a predefined method pow() instead of  (**) sign to get the power of that number.

Python Program To Check If A Number Is a Perfect Square or Not

Any number which can be expressed as the product of two whole equal numbers is classified as a perfect square. For example, 25 can be written as 5*5 hence 25 is a perfect square.

Algorithm To Check

  1. Take the input from the user
  2. Compute the square root of the given number using the math library
  3. Checking whether the  int(root + 0.5) ** 2 == number, if this evaluates to True then the number is a perfect square

Example:

import math

# Taking the input from user
number = int(input("Enter the Number: "))

root = math.sqrt(number)
if int(root + 0.5) ** 2 == number:
    print(number, "is a perfect square")
else:
    print(number, "is not a perfect square")

Output:

Enter the Number: 81
81 is a perfect square

sqrt() Function in Numpy to Calculate Square Root

numpy is a third party library and module which provides calculations about matrix, series, big data, etc. Numpy also provides the sqrt() and pow() functions and we can use these function to calculate square root.

import numy
numpy.sqrt(9)
//The result is 3
 
numpy.pow(9,1/2)
//The result is 3

Also Read:

How to Check Python Version in Various OS
Python User Input | Python Input () Function | Keyboard Input
Python Stack | Implementation of Stack in Python
How Long Does It Take To Learn Python

Conclusion

So in this tutorial, we tried to cover how to calculate Square Root In Python.
We Discussed all the methods and techniques by which you can calculate square root.

If you have still any doubts or suggestions. Do let us know in the comment section below.

Happy Coding!
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments