Square Roots in Python: Be Mindful of Operator Precedence

Looking for a language to help calculate your square roots? Python is up for the task! Just be sure to mind your precedence or disaster may strike!
python square root alpharithms

Python offers developers a robust set of language features and built-in functions. Calculating the square root of a number is a task for which Python offers several options—from operators to built-in library functions.  Python’s simple syntax makes calculating the square root possible in a single line of code and, in many cases, with only three specified terms.

There are some caveats, such as operator precedence, that might cause some issues. In this article, we’ll take a look at several approaches to calculating the square root in Python. We’ll also consider a few edge cases where syntactic oversights might lead to disastrous downstream effects.

TL;DR – Python offers developers several options. The following are the easiest to implement:

# Raise to a fractional power
16**(1/2)

>>> 4.0

# Raise to a decimal power
16**.5

>>> 4.0

# Use Math's sqrt function
from math import sqrt
sqrt(16)

>>> 4.0

Highlights

  • Python has an exponentiation operator that can be used to calculate root values.
  • Square roots can be calculated in Python using the exponentiation operator and raising values to a power of 1/2.
  • Forgetting about operator precedence can lead to disasters
  • Python also offers a sqrt() function via the standard library’s math module.

Introduction

Python lets developers select from several convenient means of calculating the square root of a number. Since Python 3, developers can use the double-asterisk syntax (**) to indicate the exponentiation of a number to a fraction or decimal. This is referred to as the Python square operator and is used for calculating exponentiation.

If we recall the laws governing fractional exponents, we can realize using the Python square operation with a fractional value can calculate root values. In this case, raising a number to the power of (1/2) is equivalent to taking the square root.

However, this is just one of several ways to calculate the square root using Python. The math module from Python’s standard library provides an optimized sqrt() function as well. In this article, we’ll take a look at each of these and discuss when one might be preferred over another. To get started, let’s take Python’s exponentiation operator for a test drive.

Python Exponentiation 101

Python interprets two successive asterisk symbols without spacing to signify the previous term being raised to the value directly proceeding the asterisks. In other words, 28 is coded as 2**8.  Let’s see what this looks like in code:

# no spaces
2**8
>>> 256

# Trailing space
2** 8
>>> 256

# Leading space
2 **8

# Double space
2 ** 8
>>> 256

# Lotsa Space
2                 **    8
>>> 256

Here we see Python following the convention of many other popular programming languages—using the double-asterisk notation for exponentiation. However, Python’s interpretation of whitespace affords developers a unique ability to mix in as much whitespace as desired.

Fractional Exponentiation

For those familiar with exponent rules, you might recall that raising a base number to a fractional exponent is the same as taking the root value of the fraction’s denominator. For a deeper dive into fractional exponents, check out this great discussion by Krista King. For our purposes here, just keep in mind the following equation:

square root exponentiation formula alpharithms
When raising a value to an exponent the numerator becomes the power of the base and the denominator is the root taken. (click to enlarge)

For our discussion, we will assume that the numerator will always be 1 (a in the image above) and the denominator will always be 2( b in the image above.) In other words—square roots are always calculated by raising a value to the 1/2 power. Let’s see how this works.

# Get the square root of 4 via fractional exponentiation
4 ** 1/2

>>> 2.0

# Get the square root of 16 via fractional exponentiation
16 ** 1/2

>>> 8.0   

# Make sure to use parenthesis when using fractional exponents
16 ** (1/2)

>>> 4.0

Here we see one very important caveat of using fractional exponents to get the square root in Python—one must use parenthesis! Python’s operator precedence dictates that exponentiation comes before division.

In the example of 16 ** 1/2 above, that means 16 is raised to the power of 1 and that result is divided by 2 (16 ** 1 = 16 / 2 = 8.) Adding the parenthesis ensures the fractional value is evaluated prior to exponentiation as such: (16 ** (1 / 2) = 16 ** .5 = 4.0.)

Decimal Exponentiation

In considering the caveat of having our fractional powers in parenthesis, we can realize using a decimal value will avoid potential confusion. That is, use the resulting value of our fraction initially rather than having that value calculated during runtime. For example, let’s see what happens when we substitute in 1/2‘s decimal value.

# Get decimal value of fraction
1 / 2

>>> 0.5

# Use decimal value as exponent
16 ** 0.5

>>> 4

# Drop the leading zero
16 ** .5

>>> 4

Here we see that no parentheses are required when pre-calculating the decimal value. Conceptually, this is no different than adding parentheses—both approaches ensure the 1/2 operation happens before the exponentiation. It’s also worth noting that we needn’t both with leading zeroes.

The Math Module

The Python standard library comes with plenty of tools to help developers tackle common programming tasks. Calculating square roots is no exception and Python offers the Math module complete with a square root function to lend a hand in calculating square root values. The code below showcases the simplicity by which this function offers utility:

from math import sqrt

# Calculate square root of 16
sqrt(16)

>>> 4.0

Final Thoughts

Python is an incredible language that simplifies the syntax for so many common development tasks it’s hard to keep count. As we’ve seen here, calculating the square root in Python is no exception—with developers having several options at their disposal. Personally, I’m a fan of using the exponentiation operator for the simple fact it avoids importing the math module. If this approach seems attractive just don’t forget to add the parentheses!

Zαck West
Full-Stack Software Engineer with 10+ years of experience. Expertise in developing distributed systems, implementing object-oriented models with a focus on semantic clarity, driving development with TDD, enhancing interfaces through thoughtful visual design, and developing deep learning agents.