Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading