Python Power Function

Syntax

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

You can alternatively use the ** syntax as follows:

Modular Exponentiation

The power function can also be used as:

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

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:

References

Python power function

Add a Comment

Your email address will not be published. Required fields are marked *