In this tutorial, three methods will be used to calculate the square root (sqrt) in python 3
- The math library.
- The ** operator and.
- The NumPy library.
1. The math library
It is important to import the math library. The math library is a built-in library in Python 3 core language. It is a core feature and very easy to use. First import the library
>>> import math
For example, we know that the square root of 16 is 4. In Python 3
>>> math.sqrt(16) 4.0
>>> from math import sqrt >>> sqrt(16) 4.0
2. The ** operator
You can use the power operator which is ** and calculate the square root of 16 and it will give you
>>> 16 ** 1/2 8.0
But the power operator will give you a minus result if you square root of -16 and that is mathematically impossible. It must return either an error value or an imaginary number i. Let us take an example
>>> x = -16 >>> x ** 1/2 -8.0 >>> sqrt(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: math domain error
As you can see from the example above,
-16 ** 1/2 = -8
To solve this, take the absolute value of -16. This will make it possible.
>>> x = -16 >>> abs(x) ** 1/2 8.0
3. The NumPy library
Numpy is a very advanced mathematical library. Widely used by the community and is used for scientific computing. If you went to learn more about NumPy, visit http://www.numpy.org/. We will cover the installation of it and use it to calculate the square root of 16.
To install it, in Windows, run the powershell terminal from the start menu, then type the following
PS > python -m pip install numpy
In Linux Ubuntu distro, make sure to install the following dependencies:-
lamda@alexpc:~$ sudo apt install python3-pip lamda@alexpc:~$ sudo -H python3 -m pip install numpy # Wide user or lamda@alexpc:~$ sudo python3 -m pip install numpy # single user
Then import sqrt from NumPy library:-
>>> from numpy import sqrt >>> sqrt(16) 4.0
The advantage of using NumPy is scalability. You can compute an multidimensional array in one single function as follow
>>> sqrt([4,16,256]) array([ 2., 4., 16.]) >>> sqrt([[1,2,3],[4,5,6],[7,8,9]]) array([[1. , 1.41421356, 1.73205081], [2. , 2.23606798, 2.44948974], [2.64575131, 2.82842712, 3. ]])
the above examples of NumPy can be extended more and take the advantage of python language to make a very pretty easy coding experience.