×

How to find square root in python

How to find Square Root of a number In Python

Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python to find the square root of a number, which is sqrt (). In this article, we will discuss the functionality of sqrt (). We will also discuss how to find the square root of a number in different scenarios without using the function.

1. Square root of a number using sqrt ():

First, we will discuss the sqrt () function:

This function is available in the math module in the Python library. So, to use the function, we need to import the math module using the import keyword:

import math

Syntax of the function:

math. sqrt (num)

Here,

num: Any number to which we need to find the square root. Condition: num >= 0

The function will return the square root of num in float or decimal form.

Example Program:

import math
print ("The square root of 4 is", math. sqrt (4))
print ("The square root of 0 is", math. sqrt (0))
print ("The square root of the decimal number: 6.7 is", math. sqrt (6.7))
num = int (input ("Enter a number: "))
root = math. sqrt (num)
print ("The square root of num =", num, "is", root)

Output:

The square root of 4 is 2.0
The square root of 0 is 0.0
The square root of the decimal number: 6.7 is 2.588435821108957
Enter a number: 4
The square root of num = 4 is 2.0

Understanding:

As observed in the above program, we imported the math module and then found the square roots of an integer number – 4, a float number – 6.7, and 0. So, we get a float output whatever input we give – int or float.

  • If we give a negative number:

The function is not defined for negative numbers. If we give a negative input, it won’t be executed due to a run-time error.

Example:

import math
print ("Square root of negative number is", math. sqrt (-6.7))

Output:

ValueError: math domain error

2. Square root of a number without using sqrt ():

Now, let us see how to find the square root of a number without using the function sqrt ():

Program:

def Bin_search(num, i, j):
    mid = (i + j) / 2;
    midsqr = mid * mid;
    if ((midsqr == num) or (abs (midsqr - num) < 0.00001)):
        return mid;
    elif (midsqr < num):
        return Bin_search (num, mid, j);
    else:
        return Bin_search (num, i, mid);
 


def Sqr_rt (num):
    i = 1;
    flag = False;
    while (flag == False):
        if (i * i == num):
            print(i);
            flag = True;
        elif (i * i > num):
 
            
            res = Bin_search (num, i - 1, i);
            print ("{0:.5f}".format(res))
            flag = True
        i += 1;


num = int (input(“Enter a number: “))
print (“The square root of num is”)
Sqr_rt (num)

Output:

Enter a number: 4
The square root of num is
2

Understanding:

We took a variable i and iterated it from i = 1. First, we checked if i *  i is equal to the number. If yes, we printed the value of i and declared num as a perfect square.

If it is not, we checked if the value of i * i is greater than num. If yes, that means the square root of the number lies between i – 1 and i.

Now, we have used the binary search technique as we know the interval. So, we found the mid-value of i – 1 and i and compared mid * mid with the number.

  • If mid * mid equals the number – mid is the root.
  • Elif mid * mid is less than the number – we search in the second half of the interval.
  • Elif mid * mid is greater than the number – we search in the first half of the interval.

We used two functions here – Sqr_rt and Bin_search. The first function is to find the square root, and the second function is to search for the square root when the number is not a perfect square in the interval.

To find the Floor square root of a number:

The floor square root of a number is the greatest whole number that is either less than or equal to the exact square root of the number.

For example, for the number 30, the square root is 5.47, but the floor square root is 5, so the output should be 5.

We have three approaches we can follow:

  1. Using the round () function.
  2. Finding the squares of all numbers from 1 till num.
  3. The efficient process.
  • First approach:

We can use the sqrt () function and the round () function. The code will be simple and take few lines.

Code:

import math
num = int (input ("Enter a number: "))
root = math.sqrt (num)
print ("The square root of the number is ", root)
floor = round (root)
print ("The floor square root of the number is: ", floor)

Output:

Enter a number: 30
The square root of the number is 5.477225575051661
The floor square root of the number is:  5
  • Second approach:

This method will find the squares of all numbers from 1 to the number. We will run into a number in the middle, say k, to which k * k will be greater than the number. It means the square root of the number lies between k-1 and k. Using binary search and finding the root, we get the square root, as we discussed earlier. But, we need floor square root, which is k – 1.

Code:

num = int (input ("Enter a number: "))
for i in range (1, num + 1):
    if (i * i > num):
        floor_rt = i - 1
        break
print ("The floor square root of num is ", floor_rt)

Output:

Enter a number: 30
The floor square root of num is 5
  • The Efficient approach:

In the above process, we found the squares of the numbers from 1 to the number. It means that we know the floor square root lies in the interval of [1, num]. Hence, we can use a binary search algorithm to find the floor root instead of all the numbers' squares.

Program:

def floor_sqrt(l, h, NUM) :
    if (l <= h) :
        mid = (l + h) // 2;
        if ((mid * mid <= NUM) and ((mid + 1) * (mid + 1) > NUM)) :
            return mid;
        elif (mid * mid < NUM) :
            return floor_sqrt(mid + 1, h, NUM);
        else :
            return floor_sqrt(l, mid - 1, NUM);
    return l;


NUM = int (input ("Enter a number: "));
print("The floor square root of the number is", floor_sqrt (0, NUM, NUM))

Output:

Enter a number: 30
The floor square root of the number is 5

Understanding:

We took a number from the user. The interval is 0 to the num. Now, we used the function floor_sqrt. Inside the function's body, we checked if the interval was valid and found the mid-value.

Now, if mid is in such a way that mid * mid <= num and mid + 1 * mid + 1 > num, we found the floor root

Elif, mid * mid is less than num; we search in the second half in [mid + 1, num].

Elif, mid + mid is greater than num; we search in the first half that is in [l, mid – 1]

Let us take an example input:

Say, num = 30,

  • [0, 30]:

Mid = 0 + 30 = 30 / 2 = 15

                  Now, mid * mid = 15 * 15 = 225 which is greater than 30. So, we go to first half which is [0, 14]

  • [0, 14]:

Mid = 0 + 14 = 14 / 2 = 7

                  Now, mid * mid = 7 * 7 = 49 which is greater than 30. So, we go to the first half which is [0, 7]

  • [0, 7]:

Mid = 0 + 7 = 7 // 2 = 3

                  Now, mid * mid = 3 * 3 = 9 which is less than 30. So, we check 4 * 4 = 16 which is also less than 30. So, we go to the second half which is [4, 7]

  • [4, 7]:

Mid = 4 + 7 = 11 // 2 = 5

                   Now, mid * mid = 5 * 5 = 25 which is less than 30. So, we check 6 * 6 = 36 which is greater than 30. WE FOUND IT

Hence, 5 is the floor square root of 30.


Related Topics

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

Google Python Class

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Python BytesIO

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

After Python, What Should I Learn

Python is a programming language used to create websites, software, and other projects. It is easy to code and easy to learn. After learning Python, there are many different directions...

4 minutes read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

What is a Script in Python

Have you ever heard that Python is a scripting language? Or when people address a Python program file as a script? Besides programming, script generally means "a written story for...

3 minutes read.

Python sorted() function

Python sorted() function The sorted() function returns a sorted list of the specified iterable object. Syntax sorted(iterable, *, key=None, reverse=False) Parameter iterable: It is a required parameter that represents the sequence to sort, list, dictionary, tuple etc. key:...

1 minute read.

Amazon rekognition using python

Amazon recognition service is an AI service which is an image labelling API (Application programming interface). In this article, we shall learn to use the AWS python boto3 module to...

3 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

Map Syntax in Python

Introduction: In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you...

6 minutes read.

ComboBox in Python

Python includes several graphical user interface (GUI) libraries, including PyQT, Tkinter, Kivy, WxPython, and PySide. Tkinter is the most commonly used GUI module in Python because it is simple and...

2 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

NOT IN operator in Python

This page contains all the information about “not in” operator in python. You can also know everything about what type of operator is “not in” in python language and where...

7 minutes read.