在python中以科学记数法打印非常大的长度

时间:2009-10-07 05:03:35

标签: python

有没有办法让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试图将long转换为float然后打印它,是否有可能让python只用科学记数法打印long而不将其转换为float?

4 个答案:

答案 0 :(得分:17)

gmpy救援......:

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

当然,我有偏见作为原始作者,仍然是gmpy的提交者,但我确实认为它可以简化这样的任务,如果没有它就可以完成一件苦差事(我不是知道一个简单的方法,没有一些附加组件,而gmpy肯定是 加载项,我在这里选择; - )。< / p>

答案 1 :(得分: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)

答案 2 :(得分:3)

这是一个仅使用标准库的解决方案:

WITH first_t AS
 (SELECT imageid, NAME, id
    FROM first_table),
second_t AS
 (SELECT imageid, NAME, id
    FROM second_table)
SELECT COUNT(src1) AS in_first_table,
       COUNT(src2) AS in_second_table,
       imageid, NAME, id
  FROM (SELECT first_t.*,
               1 AS src1,
               to_number(NULL) AS src2
          FROM first_t
        UNION ALL
        SELECT second_t.*,
               to_number(NULL) AS src1,
               2 AS src2
          FROM second_t)
 GROUP BY imageid,
          NAME,
          id
HAVING COUNT (src1) <> COUNT (src2)

答案 3 :(得分:1)

试试这个:

>>> def scientific_notation(v): # Note that v should be a string for eval()
        d = Decimal(eval(v))
        e = format(d, '.6e')
        a = e.split('e')
        b = a[0].replace('0','')
        return b + 'e' + a[1]

>>> scientific_notation('10**1000')
'1.e+1000'
>>> scientific_notation('10**1000')
'1.e+1000'
>>> sc('108007135253151**1000') # Even handles large numbers
'2.83439e+14033'