In Python, why isn't the nth root of the nth power of a number equal to the number itself?

Question:

I noticed that when I potentiate some numbers in Python, they are not the same after the inverse operation (root), for example:

>>> n = 28108234917303648763818746285031
>>> m = (n ** 5) ** (1 / 5)
>>> n == int(m)
False
>>> print(f'{m:.0f}')
28108234917303762475100368011264

Using math.pow(n ** 5, 1 / 5) yields the same result. Any ideas on why? I’d also appreciate a solution to make this consistent in Python.

Asked By: Caio Joca

||

Answers:

When you exponentiate an integer to power which is a positive integer, the result is also an integer which in python has arbitrary precision.
However, when you raise it to a non-integer power (like 1/5), the base and the result will be coerced a floating point number which has limited precision, leading to the error you see here.

>>> n = 28108234917303648763818746285031
>>> type(n ** 5)
<class 'int'>
>>> type((n ** 5) ** (1 / 5))
<class 'float'>
>>> (n ** 5) ** (1 / 5) == (float(n ** 5)) ** (1 / 5)
True
Answered By: apilat
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.