A guy in calc class was working on a more complicated solution to the approximate integration problem, and so I felt inspired to make a few improvements:
#!/usr/bin/python import sys from math import * def main(argv): try : if argv[0] == '-h': print 'usage: apxint.py <function_of_x> <lower_bound> <upper_bound> <subinterval_width>'; sys.exit(); else : function_of_x = argv[0]; a = float(eval(argv[1])); b = float(eval(argv[2])); n = float(eval(argv[3])); dx = (b-a)/n; # trapezoid Rule def f(x) : return eval(function_of_x); x = a; t = 0.0; while (x < b) : t += f(x); x += dx; t += f(x); ft = (dx/2)*t; print ("Trapezoid Rule = " + str(round(ft, 6))); # midpoint Rule x = a + (dx/2); m = 0.0; while (x <= b) : m += f(x); x += dx; print ("Midpoint Rule = " + str(round(dx*m, 6))); # Simpsons Rule x = a; s = 0.0; while (x < b) : s += f(x); x += dx; s += 4.0*f(x); x += dx; s += f(x); fs = (dx/3)*s; print ("Simpson's Rule = " + str(round(fs,6))); sys.exit(1); except IndexError: print 'usage: apxint.py <function_of_x> <lower_bound> <upper_bound> <subinterval_width>' sys.exit(2); if __name__ == "__main__": main(sys.argv[1:])



