用python在科学记数法中打印非常大的long

2024-06-17 16:19:25 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法让python用科学记数法打印非常大的long?我指的是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正在尝试将long转换为float,然后打印它,是否可以让python只以科学符号打印long,而不将其转换为float?


Tags: 标准on数字科学floatnumaprlong
3条回答

以下是仅使用标准库的解决方案:

>>> import decimal
>>> x = 10 ** 1000
>>> d = decimal.Decimal(x)
>>> format(d, '.6e')
'1.000000e+1000' 

不需要使用第三方库。这是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)

gmpy为了营救……:

>>> import gmpy
>>> x = gmpy.mpf(10**1000)
>>> x.digits(10, 0, -1, 1)
'1.e1000'

当然,作为最初的作者和gmpy的提交者,我是有偏见的,但我确实认为它简化了一些任务,比如这个任务,如果没有它,可能会是一件很麻烦的事情(我不知道没有一些插件的简单方法,而且gmpy绝对是我在这里选择的插件;-)。

相关问题 更多 >