Why number below maximum for float128 in numpy is treated as inf?

Viewed 869

I'm using numpy under python 2.7 and thought of using np.float128 in order to represent a big number like 2e315. However it´s being treated as inf although it´s smaller than the maximum representation allowed which is near to 1e4932.

In [1]: import numpy as np
In [2]: np.finfo(np.float128)
Out[2]: finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)
In [3]: np.float128(2E315)
Out[3]: inf

The previous example was tested at pythonanywhere.com with python 2.7 and numpy 1.8.1 which had following properties:

$ uname -a 
Linux harry-liveconsole4 4.4.0-83-generic #106-Ubuntu SMP Mon Jun 26 17:54:43 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

I also tested the above example under my local 64-bits machine but got error AttributeError: 'module' object has no attribute 'float128' and I have numpy 1.8.0 there.

What am I missing? What architecture should I have in order to have np.float128 under python? Is there a workaround to represent such big numbers not as inf but to leave them as I input them?

1 Answers

That's because 2E315 get's evaluated before it is passed to np.float128 and 2E315 evaluates to float('inf'):

>>> 2E315
inf

By then it is too late. Thankfully, the constructor accepts a string:

>>> import numpy as np
>>> np.float128('2e315')
2e+315
>>>

So, just to show you it works:

>>> x = np.float128('2e315')
>>> x
2e+315
>>> x // np.float128('1e312')
2000.0

This also works for me on Python 2:

>>> import sys, numpy
>>> numpy.__version__
'1.11.3'
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=13, releaselevel='final', serial=0)
>>> numpy.float128('2e315')
2e+315
>>> numpy.float128('2e315') / numpy.float128('1e312')
2000.0000000000000001
Related