Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #107539 > unrolled thread

Optimizing Memory Allocation in a Simple, but Long Function

Started byDerek Klinge <schilke.60@gmail.com>
First post2016-04-24 03:05 +0000
Last post2016-04-24 03:05 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Optimizing Memory Allocation in a Simple, but Long Function Derek Klinge <schilke.60@gmail.com> - 2016-04-24 03:05 +0000

#107539 — Optimizing Memory Allocation in a Simple, but Long Function

FromDerek Klinge <schilke.60@gmail.com>
Date2016-04-24 03:05 +0000
SubjectOptimizing Memory Allocation in a Simple, but Long Function
Message-ID<mailman.29.1461478406.32212.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web