Techno Blender
Digitally Yours.
0 11

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.

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 matha = 1b = 25# Square root of a positive numbera_sqrt = math.sqrt(a)b_sqrt = math.sqrt(b)# Printprint("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, 1×1 = 1, and 5×5 = 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 matha = 0# Square root of a zeroa_sqrt = math.sqrt(a)# Printprint("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 matha = -10# Square root of a negative numbera_sqrt = math.sqrt(a)# Printprint("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.

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 matha = 1b = 25c = 30.82d = 100e = 400.40# Method #1 - math.sqrt() functiona_sqrt = math.sqrt(a)b_sqrt = math.sqrt(b)c_sqrt = math.sqrt(c)d_sqrt = math.sqrt(d)e_sqrt = math.sqrt(e)# Printprint("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.

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 matha = 1b = 25c = 30.82d = 100e = 400.40# Method #2 - math.pow() functiona_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)# Printprint("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.

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 = 1b = 25c = 30.82d = 100e = 400.40# Method #3 - Python exponent operatora_sqrt = a**0.5b_sqrt = b**0.5c_sqrt = c**0.5d_sqrt = d**0.5e_sqrt = e**0.5# Printprint("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 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 npa = 1b = 25c = 30.82d = 100e = 400.40arr = [a, b, c]# Method #4 - Numpy square rootsa_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)# Printprint("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.

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 cmatha = 1b = 25.44c = cmath.pid = 10+10je = -100# Method #5 - Square roots of complex numbersa_sqrt = cmath.sqrt(a)b_sqrt = cmath.sqrt(b)c_sqrt = cmath.sqrt(c)d_sqrt = cmath.sqrt(d)e_sqrt = cmath.sqrt(e)# Printprint("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.

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 = 1b = 27c = 30.82d = 1000e = 400.40# Bonus #1 - Cube rootsa_cbrt = a ** (1./3.)b_cbrt = b ** (1./3.)c_cbrt = c ** (1./3.)d_cbrt = d ** (1./3.)e_cbrt = e ** (1./3.)# Printprint("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 npa = 1b = 27c = 30.82d = 1000e = 400.40arr = [a, b, c]# Bonus #1.2 - Cube roots with Numpya_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)# Printprint("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 matharr = [1, 25, 30.82]arr_sqrt = []# Bonus #2 - Square root of a Python listfor num in arr:arr_sqrt.append(math.sqrt(num))# Print# Printprint("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 matharr = [1, 25, 30.82]# Bonus #2.2 - Square root of a Python list using list comprehensionarr_sqrt = [math.sqrt(num) for num in arr]# Print# Printprint("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.

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.

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 matha = 1b = 25# Square root of a positive numbera_sqrt = math.sqrt(a)b_sqrt = math.sqrt(b)# Printprint("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, 1×1 = 1, and 5×5 = 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 matha = 0# Square root of a zeroa_sqrt = math.sqrt(a)# Printprint("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 matha = -10# Square root of a negative numbera_sqrt = math.sqrt(a)# Printprint("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.

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 matha = 1b = 25c = 30.82d = 100e = 400.40# Method #1 - math.sqrt() functiona_sqrt = math.sqrt(a)b_sqrt = math.sqrt(b)c_sqrt = math.sqrt(c)d_sqrt = math.sqrt(d)e_sqrt = math.sqrt(e)# Printprint("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.

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 matha = 1b = 25c = 30.82d = 100e = 400.40# Method #2 - math.pow() functiona_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)# Printprint("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.

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 = 1b = 25c = 30.82d = 100e = 400.40# Method #3 - Python exponent operatora_sqrt = a**0.5b_sqrt = b**0.5c_sqrt = c**0.5d_sqrt = d**0.5e_sqrt = e**0.5# Printprint("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 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 npa = 1b = 25c = 30.82d = 100e = 400.40arr = [a, b, c]# Method #4 - Numpy square rootsa_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)# Printprint("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.

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 cmatha = 1b = 25.44c = cmath.pid = 10+10je = -100# Method #5 - Square roots of complex numbersa_sqrt = cmath.sqrt(a)b_sqrt = cmath.sqrt(b)c_sqrt = cmath.sqrt(c)d_sqrt = cmath.sqrt(d)e_sqrt = cmath.sqrt(e)# Printprint("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.

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 = 1b = 27c = 30.82d = 1000e = 400.40# Bonus #1 - Cube rootsa_cbrt = a ** (1./3.)b_cbrt = b ** (1./3.)c_cbrt = c ** (1./3.)d_cbrt = d ** (1./3.)e_cbrt = e ** (1./3.)# Printprint("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 npa = 1b = 27c = 30.82d = 1000e = 400.40arr = [a, b, c]# Bonus #1.2 - Cube roots with Numpya_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)# Printprint("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 matharr = [1, 25, 30.82]arr_sqrt = []# Bonus #2 - Square root of a Python listfor num in arr:arr_sqrt.append(math.sqrt(num))# Print# Printprint("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 matharr = [1, 25, 30.82]# Bonus #2.2 - Square root of a Python list using list comprehensionarr_sqrt = [math.sqrt(num) for num in arr]# Print# Printprint("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.