def power, problem when raising power to decimals

John Machin sjmachin at
Thu Apr 17 00:21:18 CEST 2008

skanemupp at wrote:
> how do i solve power(5,1.3)?

Is this a trick question? OK, I'll bite:

 >>> 5 ** 1.3

> def power(nbr, po):
>     if po==0:
>         return 1
>     if po>0:
>         return nbr*power(nbr, po-1)
>     if po<0:
>         return 1/power(nbr, -1*po)
> also i found a link which states 0^0 isnt 1 even though every
> calculator ive tried says it is.
> it doesnt say what it is but i presume 0 then.
> but it seems the dude is wrong and it is 1?

Of the possible results of 0 ** 0 (i.e. 1, 0, and NaN), 1 seems to be 
the least implausible. It allows X ** 0 to be 1 for all X.

> dont run the code with decimals, it will never leave the function, u
> have to restart the shell(if using the standard python ide)

I presume that by "decimals", you mean "numbers that are not integers".

So you've got it into an infinite loop. Have you tried tracing through 
the first 5 or 6 gyrations? This can be done by
(a) putting a debugger breakpoint just after the start of the function
(b) using something like:
     print "power(%.6f, %.6f)" % (nbr, po))
     junk = raw_input("Press <Enter> to continue -> ")
(c) using a pencil and a piece of scrap paper, write down what is 
happening as a typical function call is executed e.g.

power(5, 1.3) => 5 * power(5, 0.3)
power(5, 0.3) => 5 * power(5, -0.7)
power(5, -0.7) => 1 / power (5, 0.7)

Then work out what extra condition you would have to test to stop it 
doing that. Then work out how to calculate the return value when that 
condition is true.


More information about the Python-list mailing list