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
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)
Try this:
>>> 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'
Here's a solution using only standard library:
>>> import decimal
>>> x = 10 ** 1000
>>> d = decimal.Decimal(x)
>>> format(d, '.6e')
'1.000000e+1000'
gmpy to the rescue...:
>>> import gmpy
>>> x = gmpy.mpf(10**1000)
>>> x.digits(10, 0, -1, 1)
'1.e1000'
I'm biased, of course, as the original author and still a committer of gmpy
, but I do think it eases tasks such as this one that can be quite a chore without it (I don't know a simple way to do it without some add-on, and gmpy
's definitely the add-on I'd choose here;-).