Optimizing Memory Allocation in a Simple, but Long Function

Chris Angelico rosuav at gmail.com
Sun Apr 24 12:19:26 EDT 2016


On Sun, Apr 24, 2016 at 1:05 PM, Derek Klinge <schilke.60 at gmail.com> wrote:
> I have been writing a python script to explore Euler's Method of
> approximating Euler's Number. I was hoping there might be a way to make
> this process work faster, as for sufficiently large eulerSteps, the process
> below becomes quite slow and sometimes memory intensive. I'm hoping someone
> can give me some insight as to how to optimize these algorithms, or ways I
> might decrease memory usage. I have been thinking about finding a way
> around importing the math module, as it seems a bit unneeded except as an
> easy reference.

Are you sure memory is the real problem here?

(The first problem you have, incidentally, is a formatting one. All
your indentation has been lost. Try posting your code again, in a way
that doesn't lose leading spaces/tabs, and then we'll be better able
to figure out what's going on.)

If I'm reading your code correctly, you have two parts:

1) class EulersNumber, which iterates up to some specific count
2) Module-level functions, which progressively increase the count of
constructed EulersNumbers.

Between them, you appear to have an O(n*n) algorithm for finding a
"sufficiently-accurate" representation. You're starting over from
nothing every time. If, instead, you were to start from the previous
approximation and add another iteration, that ought to be immensely
faster.

ChrisA



More information about the Python-list mailing list