This one instead reads the values from a CSV file containing experimental data.
Link to my previous implementation of Simspson’s rule.
[sourcecode language='python']
import csv
class simpsonCsv:
def __init__(self, filename):
reader = csv.reader(open(filename, “rb”))
xlist = []
ylist = []
for row in reader:
try:
x = float(row[0])
y = float(row[1])
except TypeError:
continue
except ValueError:
continue
xlist.append(float(x))
ylist.append(float(y))
self.len = len(xlist) - 1
self.xstart = xlist[0]
self.xend = xlist[self.len]
self.interval = self.xend / self.len
self.data = map(None, xlist, ylist)
def f(self, x):
for (u,v) in self.data:
if u == x:
return v
print “Bad x value (probably bad n): %s” % (x)
return None
def simpson(self, n):
“Approximate the definite integral of f from a to b by Simpson’s rule.”
if self.len % n != 0:
print “Error: %d mod %d is not zero but should be.” % (self.len, n)
return -1
h = float(self.xend - self.xstart)/n
si = 0.0
sp = 0.0
xk = 0.0
for i in range(1, n, 2):
xk = self.xstart + i*h
si += self.f(xk)
for i in range(2, n, 2):
xk = self.xstart + i*h
sp += self.f(xk)
s = 2*sp + 4*si + self.f(self.xstart) + self.f(self.xend)
return (h/3)*s
filename = “integral_tabela_CO2_csv.csv”
s = simpsonCsv(filename)
print s.simpson(20)
print s.simpson(40)
print s.simpson(60)
print s.simpson(100)
print s.simpson(300)
print s.simpson(600)
print s.simpson(900)
print s.simpson(1800)
[/sourcecode]
No related posts.















2 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.
cheguei aqui por causa do python (que ando a aprender aos poucos) mas o que me impressionou mesmo foi o color coding.. isto é um plugin do wordpress? por defeito no wordpress.com? será que consigo instalar no meu?
@andrezero
http://faq.wordpress.com/2007/09/03/how-do-i-post-source-code/