Last active
December 27, 2015 12:49
-
-
Save cdosborn/7328811 to your computer and use it in GitHub Desktop.
Integral approximation using the trapezoidal, midpoint, and simpson approximation technique.
This file contains 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
# the midpoint approximation of the integral of x*x from [0 1], with 10 subdivisions | |
# integral.midpoint(lambda x: x*x,0,1,10) | |
def trapezoidal(f, start, end, n, _area=0, _n=0): | |
if _n is 0: | |
return trapezoidal(f, start, end, n, _area, n) | |
elif n is 0: | |
return _area | |
else: | |
delta_x = (end - start) / (_n * 1.0) | |
x1 = start + n * delta_x | |
x2 = start + (n - 1) * delta_x | |
rect_height = (f(x1) + f(x2)) / 2.0 | |
rect_area = rect_height * delta_x | |
_area += rect_area | |
return trapezoidal(f, start, end, n - 1, _area, _n) | |
def midpoint(f, start, end, n, _area=0, _n=0): | |
if _n is 0: | |
return midpoint(f, start, end, n, _area, n) | |
elif n is 0: | |
return _area | |
else: | |
delta_x = (end - start) / (_n * 1.0) | |
xi = start + n * delta_x - delta_x / 2 | |
rect_height = (f(xi)) | |
rect_area = rect_height * delta_x | |
_area += rect_area | |
return midpoint(f, start, end, n - 1, _area, _n) | |
def simpson(f, start, end, n, _area=0, _n=0): | |
if n % 2 is 1: | |
print "Error: n must be even" | |
elif _n is 0: | |
return simpson(f, start, end, n, _area, n) | |
elif n is 0: | |
return _area | |
else: | |
delta_x = (end - start) / (_n * 1.0) | |
x0 = start + (n) * delta_x | |
x1 = start + (n - 1) * delta_x | |
x2 = start + (n - 2) * delta_x | |
rect_area = (delta_x / 3) * ((f(x0)) + 4 * (f(x1)) + (f(x2))) | |
_area += rect_area | |
return simpson(f, start, end, n - 2, _area, _n) | |
def all_approx(f, start, end, n, _area=0, _n=0): | |
print "trapezoidal: " + str(trapezoidal(f, start, end, n)) | |
print "midpoint: " + str(midpoint(f, start, end, n)) | |
print "simpson: " + str(simpson(f, start, end, n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment