DEV Community

Srinivas for ItsMyCode

Posted on • Originally published at itsmycode.com on

How to find Square Root in Python?

ItsMyCode |

In this article, you will be learning how to find square roots in Python and what are the popular square root functions in Python.

What is a Square root?

Square root, in mathematics, is a factor of a number that, when multiplied by itself, gives the original number. For example, both 3 and –3 are square roots of 9.

How to calculate the Square root in Python?

The math module in Python has sqrt() and pow() functions, using which you can calculate the square root of a given number.

Using sqrt() function

The sqrt() function takes one parameter and returns the square root of the provided number.

Syntax:

_sqrt(x) _# x is the number whose square root needs to be calculated.

Example

Let’s take a various and find the square root of a decimal, positive number, zero.

# Import math module
import math

# calculate square root of given number
print(math.sqrt(25))

# square root of 10
print(math.sqrt(10))

# square root of 0
print(math.sqrt(0))

# square root of decimal number
print(math.sqrt(4.5))
Enter fullscreen mode Exit fullscreen mode

Output

5.0
3.1622776601683795
0.0
2.1213203435596424
Enter fullscreen mode Exit fullscreen mode

The sqrt() method can take only positive numbers in case if you provide the negative number you will get a ValueError as shown below.

# Import math module
import math

# calculate square root of negative number
print(math.sqrt(-33))

Enter fullscreen mode Exit fullscreen mode

Output

Traceback (most recent call last):
  File "c:\Projects\Tryouts\main.py", line 5, in <module>
    print(math.sqrt(-33))
ValueError: math domain error
Enter fullscreen mode Exit fullscreen mode

Using pow() function

The*pow()* method can be used to compute the square root of any number. This pow() function takes two parameters and multiplies them to compute the results. This is done in order to the mathematical equation where,

x2 = y or y=x**.5

The syntax of this function is as follows:

Syntax

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

# Import math module
import math

# calculate square root of given number
print(math.pow(25,0.5))

# square root of 10
print(math.pow(10,0.5))

# square root of 0
print(math.pow(0,0.5))

# square root of decimal number
print(math.pow(4.5,0.5))
Enter fullscreen mode Exit fullscreen mode

Output

5.0
3.1622776601683795
0.0
2.1213203435596424
Enter fullscreen mode Exit fullscreen mode

The post How to find Square Root in Python? appeared first on ItsMyCode.

Discussion (0)