Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is the Square Root of a Number?
3.
Syntax of sqrt() in Python
4.
Domain of sqrt() in Python
5.
Return value of sqrt() in Python
6.
Various Ways to Calculate Square Root in Python
6.1.
Python Square Root using pow() Function
6.2.
python
6.3.
Python Square Root using Exponent Operator
6.4.
Python Square Root using sqrt()
6.5.
python
7.
Preferred Method to Find Square Root in Python
7.1.
Using Python 2.7.16
7.2.
python
7.3.
Using Python 3.8.2
8.
Example of Square Root in Python 
8.1.
python
9.
More Examples
9.1.
1. The square root of zero
9.2.
python
9.3.
2. Square Root of a positive number
9.4.
python
9.5.
3. Square root of negative numbers
9.6.
python
10.
Square Roots in the Real World
11.
Frequently Asked Questions
11.1.
Q. What do you need to import in Python to use the square root function?
11.2.
Q. How do you code a square root?
11.3.
Q. How do you do power 2 in Python?
11.4.
Q. What is the rule of square root in Python?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

How to Compute Square Roots in Python

Author Aashna Luthra
0 upvote

Introduction

Welcome Ninjas! Are you interested in knowing the Python square root? Great! You are at the right place.

The Python Square Root Function

What is the Square Root of a Number?

A number's square root is a value that yields the original number when multiplied by itself. 

If x were the square root of y, it would be written as x=√y. The root of the integers is denoted by the radical symbol  ‘√’. Here, in this blog, we will implement this square root mathematical functionality using Python.

Are you ready?

Recommended topics, Floor Division in Python, and Convert String to List Python

Syntax of sqrt() in Python

To use the sqrt() function, we need to import the math library:

import math

 

Then we can work with the sqrt() function. So, the syntax of the sqrt() function is

math.sqrt(givenValue)

 

givenValue is the number whose square root we want to find. 

Domain of sqrt() in Python

Sqrt() function in Python requires the argument to be a non-negative number. If a negative number is passed, it will raise a main domain error, indicating that the input is not valid for square root calculation.

Return value of sqrt() in Python

The function sqrt() in Python returns a floating-point number, which is the square root of the input. Suppose we pass the number 49, which is a perfect square of 7, so this function will return 7.0.

Various Ways to Calculate Square Root in Python

Python Square Root using pow() Function

The function pow() is present in the â€˜math’ module. Let's examine the Python pow() function's working. The function takes in two parameters: the first input of the pow() function is the numerical value, and the second parameter is the power of the numerical value. To calculate the square root, the second parameter in the pow() function will be 0.5.
 

For example: 

  • python

python

import math 
math.pow(144,0.5)
You can also try this code with Online Python Compiler
Run Code


Output:

output1

The pow() function only works with positive real numbers.

Also See, Intersection in Python

Python Square Root using Exponent Operator

We can use the â€˜**’ exponent operator to calculate the square root.

For example: 

144**0.5


Output:

output2

This method of calculating square root works for all positive real numbers. But it cannot be done for negative or complex values.

Must Read, Divmod in Python

Python Square Root using sqrt()

You can solve mathematical problems in code with the help of Python's math module

It has numerous helpful functions, like factorial() and the remainder(). Additionally, the library includes the python square root function, sqrt().

For using the sqrt() function, import the ‘math’ module. 

>>> import math

The interface of sqrt() is simple. It only requires one parameter, x, the square whose square root you are attempting to calculate. The square root of x is returned by sqrt() as a floating point integer. 

Syntax

math.sqrt(x)

 

Let us consider an example, we want find the square root of the number 266, so, we can write the following code:

  • python

python

import math
number = 266
result = math.sqrt(number)
print(result)
You can also try this code with Online Python Compiler
Run Code

 

Output:

16.30950643030009

Preferred Method to Find Square Root in Python

Using Python 2.7.16

Let us consider an example and try to find the square root of 1200.45 in Python version 2.7.16. So we can write the following code:

  • python

python

import math
import timeit

# Checking execution time of pow()
powtime = timeit.timeit(lambda: pow(1200.45, 0.5), number=100000)

# Checking execution time of sqrt()
sqrttime = timeit.timeit(lambda: math.sqrt(1200.45), number=100000)

# Checking execution time of the ** operator
optime = timeit.timeit(lambda: 1200.45 ** 0.5, number=100000)

print("Time taken by pow function is:")
print(powtime)

print("Time taken by sqrt function is:")
print(sqrttime)

print("Time taken by ** operator is:")
print(optime)
You can also try this code with Online Python Compiler
Run Code

 

This will give the following output:

Time taken by pow function is:
0.0317890644073
Time taken by sqrt function is:
0.0194079875946
Time taken by ** operator is:
0.00949597358704

In the example above, the timeit.timeit() function is used to measure the execution time for each operation. The number parameter determines the number of repetitions for obtaining a more accurate measurement. By running this code, you will get the execution time for each method in seconds. 

Using Python 3.8.2

Let us consider the above example and try to find the square root of 1200.45 in Python version 3.8.2. So we execute the same code in 3.8.2 and this will give us:

Time taken by pow function is:
0.008450149999589485
Time taken by sqrt function is:
0.007883119000325678
Time taken by ** operator is:
0.004768648999743164

 

So, we can clearly see that sqrt() and ** operator are the preferred methods to find the square root in Python. Along with this, it also depends which version you are using.

Example of Square Root in Python 

Suppose we are working on a geometrical project. In this project, we need to determine the length of the hypotenuse of a right-angled triangle, given the lengths of the other two sides. The Pythagoras theorem states that the square of the hypotenuse is equal to the sum of the squares of the other two sides. Let us write the code for this problem

  • python

python

import math
# Length of the sides
sideA = 12
sideB = 17

# Finding the length of the hypotenuse
hypotenuse = math.sqrt(sideA**2 + sideB**2)
print("Length of the hypotenuse is :", hypotenuse)
You can also try this code with Online Python Compiler
Run Code

 

This will give the following output:

Length of the hypotenuse is : 20.808652046684813

 

In this example, we have imported the math module to use the sqrt() function. We have defined two sides sideA and sideB as the length of sides of the right-angled triangle. Then, we calculate the length of the hypotenuse using the Pythagoras theorem, i.e., hypotenuse = sqrt(sideA**2 + sideB**2). The ** operator is used to perform the exponentiation.

More Examples

1. The square root of zero

When you provide 0 as an argument to Python's square root function, it will return 0 as the square root of 0. This behavior is consistent with the mathematical definition of the square root, which states that the square root of 0 is, indeed, 0.

Code:

  • python

python

# Python3 program to demonstrate the
# sqrt() method
# import the math module
import math
# print the square root of 0
print(math.sqrt(0))
You can also try this code with Online Python Compiler
Run Code

 

Output:

0.0

2. Square Root of a positive number

A positive number is one sort of parameter that can be passed to sqrt(). This includes both int and float types. For example, you can use sqrt() to find the square root of 49.

Code:

  • python

python

# Python3 program to demonstrate the
# sqrt() method
# import the math module
import math
# print the square root of 0
print(math.sqrt(49))
You can also try this code with Online Python Compiler
Run Code

 

Output:

7.0

3. Square root of negative numbers

Any real number's square cannot be negative. This is due to the fact that a negative product can only exist if one factor is positive and the other is negative. As a square is the product of a number and itself, it is impossible to have a negative real square.

Code:

  • python

python

# Python3 program to demonstrate the
# sqrt() method

# import the math module
import math

# print the square root of 0
print(math.sqrt(-100))
You can also try this code with Online Python Compiler
Run Code

 

Output:

Traceback (most recent call last):
 File "main.py", line 8, in <module>
   print(math.sqrt(-100))
ValueError: math domain error

Square Roots in the Real World

Square roots might seem like an abstract mathematical concept, but they play a surprisingly important role in many aspects of our daily lives. From cutting lumber to designing buildings, understanding square roots can be quite practical.

Let's explore some real-world applications of square roots:

  • Pythagorean Theorem: This fundamental theorem in geometry relates the sides of a right triangle. The formula uses square roots to find the length of the hypotenuse (the longest side) given the lengths of the other two sides. Carpenters and builders frequently use the Pythagorean theorem to ensure their cuts are precise.
  • Areas and Distances: Square roots are used to calculate areas of squares and circles, as well as distances. For instance, finding the diagonal distance across a rectangular field involves using the Pythagorean theorem and square roots.
  • Rates and Speeds: Square roots can be used to calculate rates and speeds when dealing with time and distance. For example, if you know the distance traveled and the time taken, you can find the speed using a formula that involves a square root.
  • Financial Calculations: Square roots appear in various financial calculations, such as finding the rate of return on an investment over a specific period.
  • Physics and Engineering: Square roots are fundamental in many physics and engineering applications. They are used in formulas for motion, wave behavior, and even electrical circuits.

Frequently Asked Questions

Q. What do you need to import in Python to use the square root function?

To use the square root function in Python, you need to import the "math" module using the command "import math". This module contains various mathematical functions, including "sqrt()", which can be used to calculate the square root of a number.

Q. How do you code a square root?

In the math.h header file, the sqrt() function is defined. To obtain the square root of an int, float, or long double data type, use the cast operator to explicitly convert the type to double.

Q. How do you do power 2 in Python?

In Python, the operator that can be used to execute exponent arithmetic is **. It performs the exponential calculation given two real number operands, one on either side of the operator (2**5 translates to 2*2*2*2*2). In Python, the exponent operator ** works in the same way as the pow(a, b) function.

Q. What is the rule of square root in Python?

The rule of square root using the sqrt() function in Python is that it only requires one parameter, x, the square whose square root you are attempting to calculate. The square root of x is returned by sqrt() as a floating point integer. It also requires the argument to be a non-negative number. If a negative number is passed, it will raise a ValueError.

Conclusion

In this article, we explored the python square root function. We explored different methods to calculate python square root like pow(), sqrt() and exponent operator. We also studied how negative and complex numbers’ square roots are calculated. We believe this article on python square root was helpful. To learn more about Python, check out our articles on


Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, System Design, Competitive Programming, JavaScript, etc. Enroll in our courses and refer to the problems available and mock tests. Take a look at the interview bundle and interview experiences for placement preparations.

Happy Learning Ninja!

Live masterclass