There’s more than one way to Python square roots. Learn 5 approaches to square roots in Python + some bonus advanced tricks.
After learning about 4 ways to square a number in Python, now it’s time to tackle the opposite operation - Python square roots. This article will teach you five distinct ways to take square roots in Python and will finish off with a bonus section on cube roots and square roots of Python lists.
Let’s get started by introducing the topic and addressing the potential issues you have to consider when calculating square roots in Python.
Introduction to Python Square Roots
Put simply, the square root of a number is a value that returns the same number when multiplied by itself. It’s an inverse operation of squaring.
For example, 3 squared is 9, and a square root of 9 is 3 because 3 x 3 is 9. It’s a concept that’s somewhat difficult to explain in a sentence, but you get the idea as soon as you see it in action.
Before diving into different ways to take square roots in Python, let’s go over the sets of numbers for which you can and can’t take square roots.
Square root of a positive number
Square roots only play well with positive numbers. For now, ignore the code that’s responsible for calculations and just focus on the results.
The following code snippet prints the square root for numbers 1 and 25:
import math
a = 1
b = 25
# Square root of a positive number
a_sqrt = math.sqrt(a)
b_sqrt = math.sqrt(b)
# Print
print("Square root of a positive number")
print("--------------------------------------------------")
print(f"Square root of {a} = {a_sqrt}")
print(f"Square root of {b} = {b_sqrt}")
Here’s the output:
So, 1x1 = 1, and 5x5 = 25 - that’s essentially how square roots work. But what if you were to take a square root of zero?
Square root of zero
Now, zero is neither a prime nor composite number, so we can’t find its prime factorization. For this reason, a square root of zero is zero:
import math
a = 0
# Square root of a zero
a_sqrt = math.sqrt(a)
# Print
print("Square root of a zero")
print("--------------------------------------------------")
print(f"Square root of {a} = {a_sqrt}")
Here’s the output:
Only one use case left, and that’s negative numbers.
Square root of a negative number
There’s no way to calculate a square root of a negative number by using real numbers. Two negative numbers multiplied will always result in a positive number.
Nevertheless, let’s give it a shot:
import math
a = -10
# Square root of a negative number
a_sqrt = math.sqrt(a)
# Print
print("Square root of a negative number")
print("--------------------------------------------------")
print(f"Square root of {a} = {a_sqrt}")
It results in an error:
There are ways to calculate square roots of negative numbers, and that’s by writing them as a multiple of -1. For instance, -9 can be written as -1 x 9. The result would be 3i. Stepping into the realm of imaginary numbers is out of the scope for today, so I’ll stop here.
Next, let’s go over 5 ways to tackle Python square roots.
Calculate Square Roots with the sqrt() Function
The first method is actually the one you’ve seen in the previous section. It relies on the math.pow()
function to do the trick. This module ships with the default Python installation, so there’s no need to install any external libraries.
Below is a code snippet demonstrating how to take square roots in Python using this function:
import math
a = 1
b = 25
c = 30.82
d = 100
e = 400.40
# Method #1 - math.sqrt() function
a_sqrt = math.sqrt(a)
b_sqrt = math.sqrt(b)
c_sqrt = math.sqrt(c)
d_sqrt = math.sqrt(d)
e_sqrt = math.sqrt(e)
# Print
print("Method #1 - math.sqrt() function")
print("--------------------------------------------------")
print(f"Square root of {a} = {a_sqrt}")
print(f"Square root of {b} = {b_sqrt}")
print(f"Square root of {c} = {c_sqrt}")
print(f"Square root of {d} = {d_sqrt}")
print(f"Square root of {e} = {e_sqrt}")
And here are the results:
This is probably the one and only method you’ll need, but let’s take a look at some alternatives as well.
Calculate Square Roots with the pow() Function
If squaring a number means raising it to the power of 2, then taking a square root is essentially raising it to the power of 0.5. That’s exactly the behavior you can implement with the math.pow()
function. It takes two arguments - the number and the exponent.
Let’s take a look at a couple of examples:
import math
a = 1
b = 25
c = 30.82
d = 100
e = 400.40
# Method #2 - math.pow() function
a_sqrt = math.pow(a, 0.5)
b_sqrt = math.pow(b, 0.5)
c_sqrt = math.pow(c, 0.5)
d_sqrt = math.pow(d, 0.5)
e_sqrt = math.pow(e, 0.5)
# Print
print("Method #2 - math.pow() function")
print("--------------------------------------------------")
print(f"Square root of {a} = {a_sqrt}")
print(f"Square root of {b} = {b_sqrt}")
print(f"Square root of {c} = {c_sqrt}")
print(f"Square root of {d} = {d_sqrt}")
print(f"Square root of {e} = {e_sqrt}")
The output is identical to what we had before:
Neat, but can we eliminate library usage altogether? Sure, here’s how.
Python’s Exponent Operator (**) for Taking Square Roots
The same logic from the previous function applies here. You can raise a number to the power of 0.5 with Python’s exponent operator. It does the same as math.pow(x, 0.5)
, but the syntax is shorter and doesn’t rely on any libraries.
Here’s how to use it in Python:
a = 1
b = 25
c = 30.82
d = 100
e = 400.40
# Method #3 - Python exponent operator
a_sqrt = a**0.5
b_sqrt = b**0.5
c_sqrt = c**0.5
d_sqrt = d**0.5
e_sqrt = e**0.5
# Print
print("Method #3 - Python exponent operator")
print("--------------------------------------------------")
print(f"Square root of {a} = {a_sqrt}")
print(f"Square root of {b} = {b_sqrt}")
print(f"Square root of {c} = {c_sqrt}")
print(f"Square root of {d} = {d_sqrt}")
print(f"Square root of {e} = {e_sqrt}")
The results are once again identical, no surprises here:
Next, let’s take a look at taking square roots of numbers and arrays with Numpy.
Numpy - Calculate the Root of a Number or an Array
Numpy is a go-to library for numerical computations in Python. It has a sqrt()
function built-in, and you can use it to take square roots for both numbers and arrays.
Just keep in mind the return type - it will be numpy.float64
for a single number and numpy.ndarray
for the array. Each array element will be of type numpy.float64
, of course:
import numpy as np
a = 1
b = 25
c = 30.82
d = 100
e = 400.40
arr = [a, b, c]
# Method #4 - Numpy square roots
a_sqrt = np.sqrt(a)
b_sqrt = np.sqrt(b)
c_sqrt = np.sqrt(c)
d_sqrt = np.sqrt(d)
e_sqrt = np.sqrt(e)
arr_sqrt = np.sqrt(arr)
# Print
print("Method #4 - Numpy square roots")
print("--------------------------------------------------")
print(f"Square root of {a} = {a_sqrt}")
print(f"Square root of {b} = {b_sqrt}")
print(f"Square root of {c} = {c_sqrt}")
print(f"Square root of {d} = {d_sqrt}")
print(f"Square root of {e} = {e_sqrt}")
print(f"Square root of {arr} = {arr_sqrt}")
Here’s the console output:
This is by far the most convenient method because it relies on a widely-used Python library, and the calculation procedure is the same regardless of the data type coming in.
Cmath - Take Python Square Roots of Complex Numbers
Remember the story of square roots and negative numbers? Python’s math
module raised an error but cmath
is here to save the day. This module is used to work with complex numbers.
In the code snippet below, you’ll see square roots taken from positive integers, floats, complex numbers, and negative numbers:
import cmath
a = 1
b = 25.44
c = cmath.pi
d = 10+10j
e = -100
# Method #5 - Square roots of complex numbers
a_sqrt = cmath.sqrt(a)
b_sqrt = cmath.sqrt(b)
c_sqrt = cmath.sqrt(c)
d_sqrt = cmath.sqrt(d)
e_sqrt = cmath.sqrt(e)
# Print
print("Method #5 - Square roots of complex numbers")
print("--------------------------------------------------")
print(f"Square root of {a} = {a_sqrt}")
print(f"Square root of {b} = {b_sqrt}")
print(f"Square root of {c} = {c_sqrt}")
print(f"Square root of {d} = {d_sqrt}")
print(f"Square root of {e} = {e_sqrt}")
There are no errors this time:
I’ve never had a need to use this module, but it’s good to know it exists.
Next, let’s go over some more advanced usage examples of Python square roots.
Bonus: Advanced Python Roots Topics
We’ll now shift gears and discuss a couple of more advanced topics. These include ways to calculate cube roots in Python, and take square roots of vanilla Python lists. Let’s start with the cube roots.
Cube root in Python
If taking a square root means raising a number to the power of 0.5, then the cube root must be represented by the power of 0.333, or 1/3.
Here’s how to implement this logic in Python, without any external libraries:
a = 1
b = 27
c = 30.82
d = 1000
e = 400.40
# Bonus #1 - Cube roots
a_cbrt = a ** (1./3.)
b_cbrt = b ** (1./3.)
c_cbrt = c ** (1./3.)
d_cbrt = d ** (1./3.)
e_cbrt = e ** (1./3.)
# Print
print("Bonus #1 - Cube roots")
print("--------------------------------------------------")
print(f"Cube root of {a} = {a_cbrt}")
print(f"Cube root of {b} = {b_cbrt}")
print(f"Cube root of {c} = {c_cbrt}")
print(f"Cube root of {d} = {d_cbrt}")
print(f"Cube root of {e} = {e_cbrt}")
The results are printed below:
Numpy provides an easier way to take cube roots in Python. It has a cbrt()
function built in, which stands for cube root. You can use it both on numbers and arrays, just as with square roots:
import numpy as np
a = 1
b = 27
c = 30.82
d = 1000
e = 400.40
arr = [a, b, c]
# Bonus #1.2 - Cube roots with Numpy
a_cbrt = np.cbrt(a)
b_cbrt = np.cbrt(b)
c_cbrt = np.cbrt(c)
d_cbrt = np.cbrt(d)
e_cbrt = np.cbrt(e)
arr_cbrt = np.cbrt(arr)
# Print
print("Bonus #1.2 - Cube roots with Numpy")
print("--------------------------------------------------")
print(f"Cube root of {a} = {a_cbrt}")
print(f"Cube root of {b} = {b_cbrt}")
print(f"Cube root of {c} = {c_cbrt}")
print(f"Cube root of {d} = {d_cbrt}")
print(f"Cube root of {e} = {e_cbrt}")
print(f"Cube root of {arr} = {arr_cbrt}")
Let’s take a look at the results:
Yes, it’s that easy.
Square root of a list in Python
There’s also an easy way to calculate the square root of Python lists, without Numpy. You can simply iterate over the list and take a square root of an individual list item:
import math
arr = [1, 25, 30.82]
arr_sqrt = []
# Bonus #2 - Square root of a Python list
for num in arr:
arr_sqrt.append(math.sqrt(num))
# Print
# Print
print("Bonus #2 - Square root of a Python list")
print("--------------------------------------------------")
print(f"Square root of {arr} = {arr_sqrt}")
Here’s the result:
Or, if you prefer a more Pythonic approach, there’s no reason not to use a list comprehension and simply the above calculation to a single line of code:
import math
arr = [1, 25, 30.82]
# Bonus #2.2 - Square root of a Python list using list comprehension
arr_sqrt = [math.sqrt(num) for num in arr]
# Print
# Print
print("Bonus #2.2 - Square root of a Python list using list comprehension")
print("--------------------------------------------------")
print(f"Square root of {arr} = {arr_sqrt}")
The output is identical:
And that’s how easy it is to take square roots in Python - for integers, floats, lists, and even complex numbers. Let’s make a short recap next.
Conclusion
You now know 5 different ways to calculate Python square roots. In practice, you only need one, but it can’t hurt to know a couple of alternatives. You can use the built-in math
module, opt for numpy
, or use the exponent operator and avoid libraries altogether. All approaches work, and the choice is up to you.
Stay tuned to the blog if you want to learn more basic Python concepts. Thanks for reading!
Recommended reads
- 5 Best Books to Learn Data Science Prerequisites (Math, Stats, and Programming)
- Top 5 Books to Learn Data Science in 2022
- 7 Ways to Print a List in Python
Stay connected
- Hire me as a technical writer
- Subscribe on YouTube
- Connect on LinkedIn