Skip to content

Instantly share code, notes, and snippets.

@jxnl
Last active August 29, 2015 14:00
Show Gist options
  • Save jxnl/11314809 to your computer and use it in GitHub Desktop.
Save jxnl/11314809 to your computer and use it in GitHub Desktop.
A staple of scientific data analysis and engineering this is my implementation of Simpson's Rule as the sum on a list comprehension. It takes advantage of compositing Midpoint and Trapezoid rules.
simpson = lambda (a, b, f, N): (1.0 / 3.0) * (2 * (((b - a) / N) * sum(f(v) for v in [i * ((b - a) / (2. * N)) for i in range(2 * N + 1)][1:2 * N + 1:2])) + (((b - a) / N) * ((f(a) + f(b)) / 2.0 + sum (f(v * ((b - a) / N) + a) for v in xrange(1, N )))))
def simpson(a, b, f, N):
return (1.0 / 3.0) * (2 * (((b - a) / N) * \
sum(f(v) for v in [i * ((b - a) / (2. * N))\
for i in range(2 * N + 1)][1:2 * N + 1:2]))\
+ (((b - a) / N) * ((f(a) + f(b)) / 2.0 + sum\
(f(v * ((b - a) / N) + a) for v in xrange(1, N
)))))
# int_0^1 x^2 + 2 + 2 = 1/3
print simpson(0,1,lambda x:x**2+x*2+2, 100)
# 3.33333333333
@jtmarmon
Copy link

jtmarmon commented Dec 7, 2014

why

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment