Power function

 

Hi there,

 

For this first article, we're gonna see the most basic way to implement the power function in python which only relies on "for" and "if_else" loop. Ready ? Let's get started !

 

Before opening python let's recall the formula of the power function and point out the main problem that we'll have to deal with in our algorithm :

 

Formula : f(x) = x ** (n) 

 

Main problem : We have to take care of five cases at the same time. Indeed we have to check if :

  • n = 0
  • n >0
  • n < 0
  • x > 0
  • x < 0

and act upon this information in order to get the right value in our result. In this sense a simple approach that can be used here is to divide the problem in two main cases :

  • 1st  case : x > 0
  • 2nd case : x < 0

and then divide each of these two main cases into three subsets corresponding to the different possible values of n.

 

So now let's open python and start coding our function.

 

Let's start with the case where x > 0. As we point out earlier we need that our function checks the value of n in order to get the right result. In this sense, the easiest thing to do here is to  use a if_elif loop as follows to run trough the case where :

  • n < 0
  • n = 0
  • n >= 1

Now, in the case where x < 0 we face another tricky problem : the power function become positive if n is even.

 

In order to deal with that we will need two things :

 

  • 1st  : a way to check if n is even
  • 2nd : a way to shift the negative value of our result into its opposite

Thankfully this can be done very easily as follows by using respectively the modulo (%) and the modulus function abs( ) already implemented in python. 

 

And that's it ! We have now a basic power function.

 

Full code :