Python Power Function


The power function in Python can be easily computed by importing the math module as follows:

import math
# This will print 8 which is 2 to the power 3
print pow(2, 3)

You can alternatively use the ** syntax as follows:

# This will print 8
print 2**3 

Modular Exponentiation

The power function can also be used as:

# Computes (x to the power of y) % z more efficiently
pow(x, y, z)

This is called modular exponentiation which is useful in some computer science applications especially public key cryptography, for example:

# This will print (3 to power of 3) % 5 which is equal to 2
print pow(3, 3, 5)

Power Function Example

If you like to implement your own power function from the scratch then you need to take into consideration few points:

  • If the power (y) is a negative number then compute 1/(x to the power of abs(y))
  • Fractional power can be decomposed into integer and fractional (float) components. For example 2.5 is 2 and 0.5
  • Integer component can be calculated using a regular loop. We gonna show that later.
  • Fractional power is similar to calculating a square root. Take a look at Newton’s Method for Square Root in the following article.
  • Multiplying two powers with the same base, you just add the powers together

If you apply the rules above, you should be able to come out with your own algorithm. In this article, only integer power is implemented:

# Compute x to the power of y
# Both x and y are positive integers
def POW(x, y):

	# R is the result
	R = x
	# Loop counter
	k = 1 

	# Multiply x by itself y times
	while k < y:
		R = R * x
		k = k + 1 

	# Return power
	return R

print POW(2, 3)


Python power function

Leave a Reply

%d bloggers like this: