0

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.

Caio Joca
  • 80
  • 6

1 Answers1

3

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
apilat
  • 1,370
  • 8
  • 17
  • Could also use `import math; math.isclose(m, n)`... to get a positive result in this case but ultimately... just try to not have to do that... – Jon Clements Aug 07 '22 at 11:43
  • Thank you, that makes sense. I thought floating point numbers also had arbitrary precision in Python. – Caio Joca Aug 07 '22 at 11:48
  • @CaioJoca: With the built-in `float` type, unfortunately not. From the documentation: "You are at the mercy of the underlying machine architecture" – sj95126 Aug 07 '22 at 13:28