Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #107539
| From | Derek Klinge <schilke.60@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Optimizing Memory Allocation in a Simple, but Long Function |
| Date | 2016-04-24 03:05 +0000 |
| Message-ID | <mailman.29.1461478406.32212.python-list@python.org> (permalink) |
| References | <CAGuRns8KhOFL-a1_a=0hMP=NbktoJw78ih3j4uUSbvkF8bf3pw@mail.gmail.com> |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Optimizing Memory Allocation in a Simple, but Long Function Derek Klinge <schilke.60@gmail.com> - 2016-04-24 03:05 +0000
csiph-web