Print extremely large long in scientific notation in python

后端 未结 4 2087
长发绾君心
长发绾君心 2021-02-07 13:18

Is there a way to get python to print extremely large longs in scientific notation? I am talking about numbers on the order of 10^1000 or larger, at this size the standard print

4条回答
  •  后悔当初
    2021-02-07 13:27

    No need to use a third party library. Here's a solution in Python3, that works for large integers.

    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)
    

提交回复
热议问题