Optimizing Memory Allocation in a Simple, but Long Function

Derek Klinge schilke.60 at gmail.com
Sat Apr 23 23:05:45 EDT 2016


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.

## Write a method to approximate Euler's Number using Euler's Method
import math

class EulersNumber():
def __init__(self,n):
self.eulerSteps = n
self.e = self.EulersMethod(self.eulerSteps)

def linearApproximation(self,x,h,d): # f(x+h)=f(x)+h*f'(x)
return x + h * d

def EulersMethod(self, numberOfSteps): # Repeat linear approximation over
an even range
e = 1 # e**0 = 1
for step in range(numberOfSteps):
e = self.linearApproximation(e,1.0/numberOfSteps,e) # if f(x)= e**x,
f'(x)=f(x)
return e


def EulerStepWithGuess(accuracy,guessForN):
n = guessForN
e = EulersNumber(n)
while abs(e.e -math.e) > abs(accuracy):
n +=1
e = EulersNumber(n)
print('n={} \te= {} \tdelta(e)={}'.format(n,e.e,abs(e.e-math.e)))
return e

def EulersNumberToAccuracy(PowerOfTen):
x = 1
theGuess = 1
thisE = EulersNumber(1)
while x <= abs(PowerOfTen):
thisE = EulerStepWithGuess(10**(-1*x),theGuess)
theGuess = thisE.eulerSteps * 10
x += 1
return thisE

Thanks,
Derek



More information about the Python-list mailing list