In this tutorial, I will explain the python square root. We will understand various methods to find the square root of a number in python.
How to perform square root in python
Python has an inbuild function called sqrt() using which a user can find the square root. The syntax for the sqrt() function follows the below pattern.
math.sqrt(n)
where n= any number greator than zero(n>0)
Now let’s use the math function to find the square root of 25.
import math
math.sqrt(25)
similarly, the square root of 98 can be found as
import math
math.sqrt(98)
Python square root of negative numbers
We can not use math.sqrt() function to find the square root of a negative number since it works only on numbers that are greater than or equal to zero.
>>> import math
>>> print(math.sqrt(-5))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
To find the square root we have to use the cmath module(complex math module). The syntax of cmath sqrt() follows the below pattern.
cmath.sqrt(x)
where x = any real or complex number
Now let’s use the cmath function to find the sqrt of -5.
import cmath
print(cmath.sqrt(-5))
Python square root precision
If a user wants to get the square root of a number until a specific precision, then he can use the decimal module to find the precision. Now let’s try to find the square root of 98 until 4 precision.
## import module
from decimal import *
## set precision
getcontext().prec = 4
# find square root
Decimal(98).sqrt()
Python square root in NumPy
Numpy also has an inbuild sqrt() function, using which a user can find the square root of a number in number. Below is the illustration to find the square root of 98.
import numpy as np
np.sqrt(25)
Python square root without math
So far we have seen how to find the square root in python using the math function. In this session, we will understand how to find the square root without using a math function.
We can use the exponent operator( n**0.5) to find the square root without using the math function. Let’s use this function to find the square root of 98.
98**0.5
Note: This method will work only for positive numbers.
Conclusion
I hope you liked this small tutorial about python square root. Please do let me know if you are facing any issues while following along.