7

如何获得 Python 长双字面值?我试过了

numpy.longdouble(1e309)

numpy.longdouble("1e309")

但他们俩都回来了inf。这样做的正确方法是什么?

[编辑] 下面的答案说 long double 在某些平台上被视为 double 。在我的系统上不是这样。为了证明这一点,我尝试过:

np.longdouble(2.0)**1029

在我的系统上(Mac OS 10.11)。它返回

5.7526180315594109047e+309

[ EDIT2 ] 正如建议的那样,我刚刚尝试过

 np.finfo(np.longdouble)

这使

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

在我的操作系统上。有关信息,我的 numpy 版本是 1.10.1。

4

2 回答 2

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
于 2016-04-08T16:44:51.107 回答
1

版本 2 现在可以使用(numpy 1.19.1,机器:x86-64):

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

另一个没有。

>>> np.longdouble(1e309)
inf

这不起作用,因为 1e309 首先由 python 解释器解释,它将其转换为 64 位浮点数(因为它不知道更好),然后将其发送到 numpy. 您必须以字符串文字的形式为 numpy 提供数字,以使其有机会处理数字本身。

^ x86-64 基本上意味着任何运行 Windows、MacOS 或 Linux 的个人计算机。我相信它应该适用于所有这些,因为据我所知,x86-64 都具有原生支持 80 位浮点数的 x87 浮点单元。

于 2020-10-07T00:40:43.317 回答