Techno Blender
Digitally Yours.

Python Square Roots: 5 Ways to Take Square Roots in Python | by Dario Radečić | Dec, 2022

0 43


There’s more than one way to Python square roots. Learn 5 approaches to square roots in Python + some bonus advanced tricks.

Photo by Dan Cristian Pădureț on Unsplash

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 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:

Image 1 — Square root of a positive number (image by author)

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 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:

Image 2 — Square root of a zero (image by author)

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:

Image 3 — Square root of a negative number (image by author)

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 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:

Image 4 — Math sqrt() function (image by author)

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 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:

Image 5 — Math pow() function (image by author)

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 = 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:

Image 6 — Python exponent operator (image by author)

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 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:

Image 7 — Square roots in Numpy (image by author)

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 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:

Image 8 — Square roots of complex numbers (image by author)

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 = 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:

Image 9 — Cube roots (1) (image by author)

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:

Image 10 — Cube roots (2) (image by author)

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:

Image 11 — Square root of a list (1) (image by author)

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:

Image 12 — Square root of a list (2) (image by author)

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.

Photo by Dan Cristian Pădureț on Unsplash

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 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:

Image 1 — Square root of a positive number (image by author)

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 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:

Image 2 — Square root of a zero (image by author)

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:

Image 3 — Square root of a negative number (image by author)

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 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:

Image 4 — Math sqrt() function (image by author)

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 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:

Image 5 — Math pow() function (image by author)

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 = 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:

Image 6 — Python exponent operator (image by author)

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 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:

Image 7 — Square roots in Numpy (image by author)

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 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:

Image 8 — Square roots of complex numbers (image by author)

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 = 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:

Image 9 — Cube roots (1) (image by author)

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:

Image 10 — Cube roots (2) (image by author)

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:

Image 11 — Square root of a list (1) (image by author)

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:

Image 12 — Square root of a list (2) (image by author)

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.

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment