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
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
@ajax3916882621 it really depends on what you are doing. The only thing about negative exponents is that since it’s evaluated as the inverse of the base and then raised to the exponent, if your base is 0 you are going to throw a divide by zero error.