# [ACCEPTED]-Print extremely large long in scientific notation in python-python

Accepted answer

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 6 the original author and still a committer 5 of `gmpy`

, but I do think it eases tasks such 4 as this one that can be quite a chore without 3 it (I don't know a simple way to do it without 2 *some* add-on, and `gmpy`

's definitely **the** add-on I'd choose 1 here;-).

Here's a solution using only standard library:

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

0

No need to use a third party library. Here's 2 a solution in Python3, that works for large 1 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'
```

0

Source:
stackoverflow.com

More Related questions

Cookie Warning

We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.