This article will show you how to calculate the square root, or any root, of numbers in the Python programming language.
We previously covered squaring and raising numbers to a power in this article.
What is a Root in Mathematics?
The root of a number x is the number that must be multiplied by itself a given number of times to equal the number x.
For example, the second root of 16 is 4 as 4*4 = 16. It is the second root because 4 must be multiplied by itself twice to reach the required result of 16.
The third root of 64 is 4 as 4*4*4 = 64. It is the third root because 4 must be multiplied by itself three times to reach the required result of 64.
The second root is usually called the square root. The third root is usually called the cube root. After that, there are fourth, fifth roots, and onwards – you can calculate any root, though it is less common.
Calculating Square Root In Python
Calculating the square root of a number is a common task, so Python has a built-in function for the job as part of the math library.
Here’s the syntax for the math.sqrt() function:
- n should be any number greater than 0
- math.sqrt() will return the square root of the number provided
Here’s the math.sqrt() function in action:
# Import the required math library import math # Calculate and print the square root of 9 print(math.sqrt(9))
Which will print the result:
Calculating Any Root In Python
If you want to calculate any other root number in Python, use the following syntax:
Where n is the root you wish to calculate, and x is the number you wish to calculate the root of.
In Python 3, it’s not necessary to coerce n to a float, so you can just use:
…to calculate the cubed root of 64.