Why does 1**2**3**4**5 raise a MemoryError?

morphex morphex at gmail.com
Sun Mar 31 08:07:08 EDT 2013


Aha, OK.  Thought I found a bug but yeah that makes sense ;)

While we're on the subject, wouldn't it be nice to have some cap there so that it isn't possible to more or less block the system with large exponentiation?

On Sunday, March 31, 2013 9:33:32 AM UTC+2, Steven D'Aprano wrote:
> On Sat, 30 Mar 2013 23:56:46 -0700, morphex wrote:
> 
> 
> 
> > Hi.
> 
> > 
> 
> > I was just doodling around with the python interpreter today, and here
> 
> > is the dump from the terminal:
> 
> > 
> 
> > morphex at laptop:~$ python
> 
> > Python 2.7.3 (default, Sep 26 2012, 21:53:58) [GCC 4.7.2] on linux2
> 
> > Type "help", "copyright", "credits" or "license" for more information.
> 
> >>>> 1**2
> 
> > 1
> 
> >>>> 1**2**3
> 
> > 1
> 
> >>>> 1**2**3**4
> 
> > 1L
> 
> >>>> 1**2**3**4**5
> 
> > Traceback (most recent call last):
> 
> >   File "<stdin>", line 1, in <module>
> 
> > MemoryError
> 
> >>>> 
> 
> >>>> 
> 
> > Does anyone know why this raises a MemoryError?  Doesn't make sense to
> 
> > me.
> 
> 
> 
> Because exponentiation is right-associative, not left.
> 
> 
> 
> 1**2**3**4**5 is calculated like this:
> 
> 
> 
> 1**2**3**4**5
> 
> => 1**2**3**1024
> 
> => 1**2**373...481  #  489-digit number
> 
> => 1**(something absolutely humongous)
> 
> => 1
> 
> 
> 
> except of course you get a MemoryError in calculating the intermediate 
> 
> values.
> 
> 
> 
> In other words, unlike you or me, Python is not smart enough to realise 
> 
> that 1**(...) is automatically 1, it tries to calculate the humongous 
> 
> intermediate result, and that's what fails.
> 
> 
> 
> For what it's worth, that last intermediate result (two to the power of 
> 
> the 489-digit number) has approximately a billion trillion trillion 
> 
> trillion trillion trillion trillion trillion trillion trillion trillion 
> 
> trillion trillion trillion trillion trillion trillion trillion trillion 
> 
> trillion trillion trillion trillion trillion trillion trillion trillion 
> 
> trillion trillion trillion trillion trillion trillion trillion trillion 
> 
> trillion trillion trillion trillion trillion trillion digits.
> 
> 
> 
> (American billion and trillion, 10**9 and 10**12 respectively.)
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> Steven




More information about the Python-list mailing list