×

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 Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Python Validator

Validator  The validator is a library available in the python programming language. The library in python consists of all the related modules which can be imported to perform the required operation....

3 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Convert int to Float in Python using Pandas

Introduction We have already learnt about how to convert float variables to int. Now let us know how to convert int variables to float So let us create another Dataset on which...

2 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.

Python Filter List

To filter a list, we use filter () method function. The filter () will test every element true or not in the sequence. Syntax: Filter(function, sequence) Parameters: Function: Function that check and verifies if...

2 minutes read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python. Now, let us understand what pointers are Pointers Pointers are special variables used to store the...

3 minutes read.

Recursive Multiplication Python

Recursive Multiplication Python In this tutorial, we will learn how to write a Python program to get the multiplication of two numbers using the recursive approach. In the recursive multiplication approach, we...

2 minutes read.

Python coding platform

Python is a popular general-purpose programming language with many applications. High-level data structures, datatypes, dynamic binding, and many other features make it useful for both designing complex applications and "glue...

6 minutes read.

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.