在Python中以科学计数法打印极大整数

16 投票
4 回答
12381 浏览
提问于 2025-04-15 14:52

有没有办法让Python以科学计数法打印非常大的长整型数字?我说的是像10的1000次方这样的大数字,到了这个大小,标准的打印方式"%e" % num就不管用了。

举个例子:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "%e" % 10**100
1.000000e+100
>>> print "%e" % 10**1000
Traceback (most recent call last):
  File "", line 1, in 
TypeError: float argument required, not long

看起来Python在尝试把这个长整型转换成浮点数再打印出来,那有没有办法让Python直接以科学计数法打印这个长整型,而不把它转换成浮点数呢?

4 个回答

5

不需要使用第三方库。这里有一个用Python3写的解决方案,可以处理大整数。

def ilog(n, base):
    """
    Find the integer log of n with respect to the base.

    >>> import math
    >>> for base in range(2, 16 + 1):
    ...     for n in range(1, 1000):
    ...         assert ilog(n, base) == int(math.log(n, base) + 1e-10), '%s %s' % (n, base)
    """
    count = 0
    while n >= base:
        count += 1
        n //= base
    return count

def sci_notation(n, prec=3):
    """
    Represent n in scientific notation, with the specified precision.

    >>> sci_notation(1234 * 10**1000)
    '1.234e+1003'
    >>> sci_notation(10**1000 // 2, prec=1)
    '5.0e+999'
    """
    base = 10
    exponent = ilog(n, base)
    mantissa = n / base**exponent
    return '{0:.{1}f}e{2:+d}'.format(mantissa, prec, exponent)
9

这里有一个只用标准库的解决方案:

>>> import decimal
>>> x = 10 ** 1000
>>> d = decimal.Decimal(x)
>>> format(d, '.6e')
'1.000000e+1000' 
18
>>> import gmpy
>>> x = gmpy.mpf(10**1000)
>>> x.digits(10, 0, -1, 1)
'1.e1000'

当然,我有点偏见,因为我是gmpy的原作者,现在还是它的维护者。但我真的觉得这个工具能让一些任务变得简单很多,尤其是像这种没有它的话会很麻烦的事情。我不知道没有某些额外工具的简单方法,而gmpy绝对是我在这里会选择的那个工具;-。

撰写回答