Last active
August 29, 2015 14:00
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 ))))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why