6

How to get a Python long double literal? I have tried with

numpy.longdouble(1e309)

and

numpy.longdouble("1e309")

but both of them just return inf. What would be the right way to do that?

[EDIT] An answer below says that long double is treated as double in some platform. It is not the case on my system. To show this, I have tried:

np.longdouble(2.0)**1029

on my system (Mac OS 10.11). It returns

5.7526180315594109047e+309

[EDIT2] As suggested, I just tried

 np.finfo(np.longdouble)

which gives

 finfo(resolution=1e-18, 
       min=-1.18973149536e+4932, 
       max=1.18973149536e+4932, 
       dtype=float128)

on my OS. For info, my numpy version is 1.10.1.

zell
  • 8,226
  • 7
  • 41
  • 91
  • Seems like it is somewhat duplicate of this thread: http://stackoverflow.com/questions/18536820/numpy-longdouble-arithmetic-does-not-seem-to-be-in-long-double-with-conversion – Stanley Kirdey Apr 08 '16 at 16:57
  • What NumPy version are you on? It looks like this [may have been fixed](https://github.com/numpy/numpy/issues/4381) on August 28, 2015, so the latest version of NumPy should have the fix. I don't have access to a 1.10 install to check at the moment. – user2357112 supports Monica Apr 08 '16 at 16:57
  • @user2357112 numpy version 1.10.1. – zell Apr 08 '16 at 17:04

2 Answers2

1

On some platforms long double is essential the same as double. From numpy documentation:

NPY_LONGDOUBLE

The enumeration value for a platform-specific floating point type which is at least as large as NPY_DOUBLE, but larger on many platforms.

Sometimes long double is a 80-bit float (but not 128 bit, as many people would expect). You may check with:

numpy.finfo(numpy.longdouble)

Consider the following answers as well:

  1. https://stackoverflow.com/a/25481654/2370124
  2. https://stackoverflow.com/a/18537604/2370124

You may also try this:

n = numpy.longdouble(1e300) * 1e9
Community
  • 1
  • 1
Roman Kh
  • 2,358
  • 1
  • 16
  • 15
1

Version 2 works now (numpy 1.19.1, machine: x86-64):

>>> np.longdouble('1e309')
1e+309

The other one doesn't.

>>> np.longdouble(1e309)
inf

This doesn't work because 1e309 is first interpreted by the python interpreter, which converts it into a 64 bit floating point number (because it doesn't know any better) and THEN send it to numpy. You have to give numpy the number in form of a string literal to give it a chance to process the number itself.

^ x86-64 means essentially any personal computer running Windows, MacOS or Linux. I believe it should work on all of them, because as far as i know x86-64 all have the x87 floating point unit that natively supports 80 bit floats.

Jim
  • 581
  • 4
  • 9