Python Exponent Guide: 5 Methods for Exponentiation and Applications

Kimberly FesselKimberly Fessel

If you’ve ever calculated a circle’s area from its radius or checked your account balance with compound interest, you’ve used . They’re an essential part of many of the world’s most famous equations (Hello, E = mc2!), and of course, you can code exponents in Python.

What may surprise you, however, is the sheer number of ways to perform in Python. In this article, we’ll cover not 1, not 2, but 5 different Pythonic techniques to raise a value to a . You’ll need to carefully consider your options when selecting an exponentiation method for your problems, so keep reading for a head-to-head performance breakdown along with a few edge-case “gotchas.”

What is Exponentiation in Python?

Exponentiation in Python follows similarly to mathematics. When we raise a value (x) to a power (p), you can start by thinking of multiplying that value by itself p times.

The most common method for raising a value to a power in Python is with the exponent operator, which is represented by two asterisks, **.

Method 1: The Exponent Operator (**)

You’ll frequently see exponentiation in Python with the , **, sometimes referred to as the power operator. Just place it between the base and the power you want to raise it to. For instance:

python
print(5 ** 2) # Expected result:# 25

Python interprets this as 5 raised to the power 2, or 5 squared, and returns your result, 25.

Here are a few more examples for further illustration:

python
print(2 ** 4)print(29 ** 1)print(7 ** 0) # Expected result:# 16# 29# 1

Operator Precedence in Code Examples

Python follows the (parentheses, exponentiation, multiplication and division, addition and subtraction) convention for . When you include multiple operators in one calculation, Python begins by evaluating expressions in parentheses from the inside out. Next, it performs all exponentiation before completing any multiplication and division calculations from left to right. Python saves addition and subtraction for last, again from left to right.

Check out these examples to see arithmetic precedence in action:

python
print(3 + 3 ** 2)print((3 + 3) ** 2)print(9 - 2 ** 3 * 3) # Expected result:# 12# 36# -15

Negative Values

You’ve seen Python’s exponent operator for non-negative values, but what happens when the base or the power dips below zero? Let’s start with the math.

Negative Base

In mathematics, multiplying a negative value by itself gives you a positive result. For example

(1)2=11=1(-1)^2 = -1 · -1 = 1

That means any time you raise a negative base to an even power, the negatives cancel out with each other to yield a positive result. If you raise a negative number to an odd power, however, one negative sign won’t have a partner to cancel with, and you’ll be left with a negative-valued result.

Python works like this, too, with one big caveat. You must put parentheses around the negative value in your exponentiation. Exponentiation gets higher precedence than subtraction, so without the parentheses, Python executes the exponentiation first and recognizes the negative after the fact. Here’s that situation in code:

python
print(-3 ** 2)print((-3) ** 2) # Expected result:# -9# 9

Negative Exponent

If, instead, you would like to raise a value to a negative exponent, you’ll just need to remember what that means mathematically. Raising to a negative exponent in math means the same as taking one over the value raised to the positive power.

The negative sign tells you the calculation should take place in the .

Python also follows this convention:

python
print(2 ** -2) # Expected result:# 0.25

Raising 2 to -2 gives us ¼, returned as the Python 0.25.

Fractional Exponents

Python also accepts fractional, or decimal, exponents. Raising a base to a fractional power has the same effect as finding its . For instance, you can find the square root of 36 by raising it to the ½, or 0.5, power:

python
print(36 ** 0.5) # Expected result:# 6.0

Notice that you’ll receive a float when you enter a fractional (decimal) exponent, unless you begin from a negative base, in which case your result will be a

Floating-Point Arithmetic and Precision

When you supply the exponent operator with for both the base and exponent, Python gives you an int output. If either value is a floating-point number, on the other hand, you’ll receive a float back from Python.

Python’s floating-point numbers typically have about 15-17 decimal digits of precision. You may land on exact values when processing fractional exponents, but then again, you may not. Taking the cubed root of 125 may return a value extremely close, but not quite equivalent to, 5:

python
print(125 ** (1/3)) # Expected output:# 4.999999999999999, or some other value close to 5

Since you expect approximate values for floats, you can safeguard your code by not comparing them directly against integers with the equality operator (==). Try the function isclose() from the math to check for instead:

python
import mathprint(math.isclose(27 ** (1/3), 3)) # Expected result:# True

Method 2: Built-in pow() Function

Python comes with a called pow() for raising a base value to a power. pow() comes with standard Python; you won’t need to import any extra modules or libraries to use it. It has two required arguments: the base and the exponent.

python
print(pow(5, 2))print(pow(-3, 2))print(pow(2, -2))print(pow(36, 0.5)) # Expected result:# 25# 9# 0.25# 6.0

Modular Exponentiation

You’ll find the major difference between the exponent operator (**) and pow() when adding a third, optional argument to pow(). You can also pass a modulo argument, mod, to the pow() function. So pow(x, p, m) calculates:

You can think of this as first computing the exponentiation and then doing the modulo operation. For example:

python
print(pow(3, 2, 5))print(pow(2, 4, 13)) # Expected result:# 4# 3

Methods 3 and 4: math.pow() and math.exp()

Your third and fourth options for doing exponentiation in Python come from the math module.

math.pow()

The math.pow() function works similarly to **; however, math.pow(x, p) always returns a floating-point number. You may pass int or float arguments, but the function immediately converts inputs to floating-point values.

python
import mathprint(math.pow(5, 2)) # Expected output:# 25.0

You may choose to use math.pow() if you explicitly want a float for compatibility with other scientific computing functions.

math.exp()

The math module’s exp(x) raises , e (≈ 2.7182818…), to the power x. It also always returns a float. It’s a carefully optimized function designed not to lose precision.

python
import mathprint(math.exp(3))print(math.exp(-2)) # Expected output:# 20.085536923187668# 0.1353352832366127

Method 5: numpy.power()

The NumPy library comes with a function for doing exponentiation. Call numpy.power(x, p) to raise x to the power p. Unlike Python’s built-in exponentiation, numpy.power() works when x and/or p are . It also uses optimized, compiled routines, making it significantly faster than Python loops for large datasets.

python
import numpy as npprint(np.power(5, 2))print(np.power([1, 2, 3, 4], 3))print(np.power([1, 2, 3, 4], [[2], [-1.]]))# Expected output:# 25# [ 1  8 27 64]# [[ 1.          4.          9.         16.        ]#  [ 1.          0.5         0.33333333  0.25      ]]

In the final example, NumPy uses to align shapes between the two arrays, applying element-wise exponentiation across all combinations of values. If you encounter any issues with negative or fractional exponents, you may need to convert inputs to floats (as we did with -1. in the final example) so NumPy can correctly compute non-integer results. 

Which Method Should You Use for Mathematical Calculations? 

Speed is just one factor when choosing between the multiple ways to do exponentiation in Python. You’ll also want to consider the computation type and return type of each technique. Below you’ll find a handy table to put it all together.

Method

Computation Type

Output Type

Best Use Case

Key Advantage

x ** p

Scalar

int, float, or complex

General-purpose

Simple and flexible

pow(x, p)

Scalar

int, float, or complex

Same as **

Functional form

pow(x, p, m)

Modular

int

Large exponent with modulus

Fast, avoids huge numbers

math.pow(x, p)

Scalar

float

Explicit float exponentiation

Consistent float behavior

np.power(x, p)

Vectorized

ndarray

Array-based computations

Fast, supports broadcasting

Applications of Exponentiation

Exponentiation shows up in plenty of real-world problems involving or decay, , and binary growth rates for computer memory sizes. Whether your interests lie in finance, biology, data science, data analysis, machine learning, or cryptography, you’ll need exponents to perform calculations. Here are a few of the many ways exponentiation comes up in practice.

Compound Interest

The classic formula for calculating compound interest arrives at a final amount, A, by multiplying your principal investment, P, with an expression involving your annual interest rate, r, the number of times interest compounds yearly, n, and the time in years, t:

This formula involves exponentiation, which you can translate into Python code like the following for an initial $1,000 investment at 5%, compounded monthly over 10 years:

python
P = 1000r = 0.05n = 12t = 10 A = P * (1 + r/n) ** (n*t)print(A)# Expected output:# 1647.00949769028

Sigmoid Function

The sigmoid function is used in machine learning for binary classification. The sigmoid function, or logistic function, lies at the heart of the algorithm.

where z is a of the input features:

z=β0+β1x1+...+βnxnz = β₀ + β₁x₁ + ... + βₙxₙ

The sigmoid function takes any input from negative to positive infinity and maps it to a value between 0 and 1, which is perfect for binary probabilities.

You can code up your own sigmoid function in Python by leveraging math.exp():

python
import mathdef sigmoid(z):    return 1/(1 + math.exp(-z)) print(sigmoid(0))print(sigmoid(2))print(sigmoid(-2))# Expected output:# 0.5# 0.8807970779778823# 0.11920292202211755

RSA Algorithm

The is a public-key cryptosystem that enables secure communication, digital signatures, and key exchange. It uses exponentiation with a modulus to securely encode and decode messages. The algorithm relies on the fact that modular exponentiation is easy to compute, but hard to reverse without the private key.

Here’s a simple demonstration of the RSA algorithm in Python where we use pow(x, p, m) for fast modular exponentiation:

python
# Public keye = 17n = 11413# Private keyd = 3953# MessageM = 7501# EncryptC = pow(M, e, n)# DecryptM_decrypted = pow(C, d, n)print("Encrypted:", C)print("Decrypted:", M_decrypted)# Expected result: # Encrypted: 8077# Decrypted: 7501

Wrapping Up

You can calculate exponents in Python with many different techniques. You’ll typically use the standard exponent operator (**), but keep other variants in mind for modular exponentiation (pow(x, p, m)) or vectorized exponentiation (numpy.power(x, p)). Just remember to consider speed as well as computation type and data type when selecting the right method for your use case. 

Try out the AI Tutor to continue your personal exponentiation growth. You can kick off your dialogue using this prompt:

Join the Community

roadmap.sh is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Rank  out of 28M!

354K

GitHub Stars

Star us on GitHub
Help us reach #1

+90kevery month

+2.8M

Registered Users

Register yourself
Commit to your growth

+2kevery month

47K

Discord Members

Join on Discord
Join the community

RoadmapsGuidesFAQsYouTube

roadmap.shby@nilbuild

Community created roadmaps, best practices, projects, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh·Terms·Privacy·

ThewNewStack

The top DevOps resource for Kubernetes, cloud-native computing, and large-scale development and deployment.