Search code examples
pythonmathlargenumberexponentiation

Difference between Python built-in pow and math pow for large integers


I find that for large integers, math.pow() does not successfully give its integer version.

(I got a buggy Karatsuba multiplication when implemented with math.pow).

For instance:

>>> a_Size=32
>>> pow(10,a_size) * 1024
102400000000000000000000000000000000
>>> math.pow(10,a_size) * 1024
1.024e+35
>>> int(math.pow(10,a_size) * 1024)
102400000000000005494950097298915328

I went with 10 ** a_size with correct results for large integers.

For floats, visit Difference between the built-in pow() and math.pow() for floats, in Python?

Please explain why this discrepancy is seen for math.pow. It is observed only from 10 power of 23 and higher.


Solution

  • math.pow() always returns a floating-point number, so you are limited by the precision of float (almost always an IEEE 754 double precision number). The built-in pow() on the other hand will use Python's arbitrary precision integer arithmetic when called with integer arguments.