Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour when raising numbers to the power of zero in Python [duplicate]

Tags:

python

math

I am using Python 2.7.5. When raising an int to the power of zero you would expect to see either -1 or 1 depending on whether the numerator was positive or negative.

Typing directly into the python interpreter yields the following:

>>> -2418**0
-1

This is the correct answer. However when I type this into the same interpretter:

>>> result = -2481
>>> result**0
1

the answer is 1 instead of -1. Using the complex builtin as suggested here has no effect on the outcome.

Why is this happening?

like image 970
jhrf Avatar asked Sep 20 '25 03:09

jhrf


2 Answers

Why would you expect it to be -1? 1 is (according to the definition I was taught) the correct answer.

The first gives the incorrect answer due to operator precedence.

(-1)**0 = 1

-1**0 = -(1**0) = -(1) = -1

See Wikipedia for the definition of the 0 exponent: http://en.wikipedia.org/wiki/Exponentiation#Zero_exponent

like image 172
Wolph Avatar answered Sep 22 '25 18:09

Wolph


-2418**0 is interpreted (mathematically) as -1 * (2418**0) so the answer is -1 * 1 = -1. Exponentiation happens before multiplication.

In your second example you bind the variable result to -1. The next line takes the variable result and raises it to the power of 0 so you get 1. In other words you're doing (-1)**0.

n**0 is 1 for any real number n... except 0: technically 0**0 is undefined, although Python will still return 0**0 == 1.

like image 42
Alex Riley Avatar answered Sep 22 '25 18:09

Alex Riley