Search code examples
pythondebuggingmpmath

mpmath library magnitude of number bug?


In the documentation of mpmath library page 8 it mentioned that

There is no restriction on the magnitude of numbers

>>> print(mpf(2)**32582657 - 1)
1.24575026015369e+9808357

and I checked that this code did work. However, in the same script I found that

mp.mpf(1e309)
mpf('+inf')

Is this a bug? How to set mpmath library to arbitrary magnitude of number?


Solution

  • No, it's not a bug.

    In your first code snippet mpf(2)**32582657 will dispatch into custom raise-to-power operator **, which will make use of the arbitrary precision functionality.

    In your second code snippet 1e309 is a number literal, that will be parsed by the Python interpreter into a architecture native floating point number and 309 is an exponent to large to fit into the underlying IEEE754 format, before it even reaches mpmath

    Instead, if you issued

    mp.mpf(10)**309
    

    you'd get the expected result

    mpf('1.0e+309')