Is there another method to do exponentiation other than the ** operator?


#1

Question

Is there another method in Python to perform exponentiation other than the ** operator?

Answer

Yes, the Python math library has a pow() function which can perform exponentiation. The primary difference between the ** operator and the pow() function is that the pow() function will convert the numbers to floating point while the ** operator will not.


#2

Then there is the way the computer does it… repeat addition.

Inputs are A and B.
To R add A and take away 1 from the B register. 
Repeat until the B register is 1. 

That gives us a * b.

>>> def a_x_b(a, b):
	r = a
	while b > 1:
		r += a
		b -= 1
	return r

>>> a_x_b(6, 7)
42
>>> 

I’m not sure a computer will follow this simple algorithm, so am truly winging it from here…

>>> def a_xx_b(a, b):
	r = a
	while b > 1:
		r = a_x_b(r, a)
		b -= 1
	return r

>>> a_xx_b(3, 3)
27
>>> a_xx_b(2, 10)
1024
>>> 

#3

Here it is, refactored into a single function …

def a_xx_b(a, b):
    r = a
    while b > 1:
        xa = r
        xb = a
        xr = xa
        while xb > 1:
            xr += xa
            xb -= 1
        r = xr
        b -= 1
    return r

Steps performed:

  • The variables in the a_x_b function were renamed by prepending their names with x.
  • The body of the a_x_b function was pasted into the a_xx_b function immediately following its call to the the a_x_b function.
  • The indentation was adjusted to accommodate the pasted code.
  • Right above where the pasting was done, assignments were made from what had been the arguments in the function call to what had been the renamed parameters of a_x_b function.
  • The return statement from the a_x_b function was replaced by an assignment of the result to the variable, r, that had originally received the result of the function call.
  • The call to the a_x_b function was removed.