 # Does exponentiation in Python work with negative exponents?

### Question

In this exercise, the exponent operator is used for positive exponents. Does exponentiation work with negative exponents as well?

### Answer

Yes, in Python, exponentiation does work with negative exponent values, the same way it would apply in mathematics. When performing exponentiation with a negative exponent, it is the same as getting the inverse of exponentiation done with the exponent as a positive value.

#### Example code

``````base = 2
exp = -1

# Both of these results will be 0.5
result1 = base ** exp
result2 = 1 / base ** exp
``````

edited April 28, 2020

``````# result2 = 1 / (base ** -(exp))  =>  incorrect
``````
15 Likes

8 posts were split to a new topic: 2nd question in this exponent excercise

Should not result 2 = 1 / (base ** (exp)) without the negative in front of the exp since it is already being divided?

5 Likes

Good catch. The example doesn’t look like it was tested. (Yours truly is guilty of this, sometimes, too.)

``````>>> 2 ** -1
0.5
>>> 1 / 2 ** -1
2.0
>>> 1 / 2 ** 1
0.5
>>>
``````

Going to edit this topic to correct the error.

6 Likes

I think that you were right the first time. Since exp is assigned -1, you would have to negate that when the number is in the denominator.

``````>>> 2 ** -1
0.5
>>> 1/2**-1
2.0
>>> 1/2**1
0.5
>>> base=2
>>> exp=-1
>>> base**exp
0.5
>>> 1/base**exp
2.0
>>> 1/base**-(exp)
0.5
``````

I agree. The first time was ok.

I also tried & checked the following syntax

``````result2 = 1 / base ** (-exp)
``````

All of them prints “0.5”

Yes, you and @marioguvi are both correct. The negative is needed in front of the exp to avoid the denominator going to the top and making it 2.0 rather than 0.5. In other words:

``````2 ** -1 = 1 / (2 ** 1) = 1/2

1/(2 ** -(-1)) = 1/(2 ** 1)  = 1/2     ---> The negative in front of
the exp cancels out to make it positive and thus 1/2. Otherwise it would be:

1/(2 ** (-1)) = 1/(1/ (2**1)) = 1/(1/2) = 2
``````

Sorry @mtf for the confusion!

1 Like