Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print extremely large long in scientific notation in python

Tags:

python

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 "%e" % num fails.

For example:

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

It appears that python is trying to convert the long to a float and then print it, is it possible to get python to just print the long in scientific notation without converting it to a float?

like image 477
sligocki Avatar asked Oct 07 '09 05:10

sligocki


People also ask

How do I get rid of E+ in Python?

How do you stop e+ in Python? Use a string literal to suppress scientific notation Use the string literal syntax f"{num:. nf}" to represent num in decimal format with n places following the decimal point.

How do you use very large numbers in Python?

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate.


1 Answers

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;-).

like image 108
Alex Martelli Avatar answered Oct 14 '22 11:10

Alex Martelli