-1

I am performing calculation in python that results in very large numbers. The smallest of them is 2^10^6, this number is extremely long so I attempted to use format() to convert it to scientific notation. I keep getting an error message stating that the number is too large to convert to a float.

this is the error I keep getting:

 print(format(2**10**6, "E"))

OverflowError: int too large to convert to float

I would like to print the result of 2^10^6 in a way that is concise and readable

Xenon8864
  • 1
  • 1
  • Your proposed format will show the example number as `2^` followed by about 3 million digits. Is that the improvement you are looking for? – Jongware Feb 23 '20 at 20:50
  • https://stackoverflow.com/questions/17973278/python-decimal-engineering-notation-for-mili-10e-3-and-micro-10e-6 – Pete Marise Feb 23 '20 at 20:54
  • I tried the method in the provided link before posting but I got a similar error message about the number being to large to convert to float – Xenon8864 Feb 23 '20 at 20:59
  • It would help if you posted a snippet of your code that produces the error message. See [ask] for other advice. BTW welcome to Stack Overflow! Check out the [tour]. – wjandrea Feb 23 '20 at 21:00
  • I don't know what `2^10^6` is. In python `^` is the XOR operator. – tdelaney Feb 23 '20 at 21:09
  • `format(2*10**6, "E")` ? – tdelaney Feb 23 '20 at 21:10

1 Answers1

2

You calculated 2 raised to the 10th then raised to the 6th power. If your aim is "2 times 10 to the sixth", then 2*10**6 is what you want. In python that can also be expressed by 2E6 where E means "to the 10th power". This is confusing when you are thinking in terms of natural logs and Euler's Number e.

You can also use the decimal.Decimal package if you want to side step decimal to binary float problems. In python, floats expressed in decimal are rounded to the nearest binary float. If you really did want the huge number, Decimal can handle it.

>>> Decimal("2E6")
Decimal('2E+6')
>>> Decimal("2")*10**6
Decimal('2000000')
>>> Decimal("2")**10**6
Decimal('9.900656229295898250697923616E+301029')

For printing, use the "g" format

>>> d = Decimal('2')**10**6
>>> format(d,'g')
'9.900656229295898250697923616e+301029'
>>> format(d,'.6g')
'9.90066e+301029'

>>> "{:g}".format(d)
'9.900656229295898250697923616e+301029'
>>> "{:.6g}".format(d)
'9.90066e+301029'
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • Arguably, 2 million is not *that* a "very large number". It's the number of millicents in $20, for example. OP may want to clarify whether you are right, though. – Jongware Feb 23 '20 at 22:11
  • I am trying to print the result of 2 to the 10 to the 6, the decimal function did not work with it when I used it. Are there other ways to condense numbers this large? – Xenon8864 Feb 23 '20 at 22:24
  • @Xenon8864 - added example for printing – tdelaney Feb 23 '20 at 23:10