Calculus UNIT506: Pythonic Riemann Sums?

2411 days ago by MATH4R2013

f="-x**2" a=1 b=5 n=8 def lSum(f,a,b,n): h=(b-a)/n l=sum([f(a+i*h)*h for i in range(n)]) return l def rSum(f,a,b,n): h=(b-a)/n l=sum([f(a+i*h)*h for i in range(n)]) return l-f(a)*h+f(b)*h def tSum(f,a,b,n): h=(b-a)/n l=sum([f(a+i*h)*h for i in range(n)]) r=l-f(a)*h+f(b)*h return (r+l)/2 def tError(f,a,b,n): h=(b-a)/n l=sum([f(a+i*h)*h for i in range(n)]) r=l-f(a)*h+f(b)*h return (r-l)/2 l=lSum(lambda x: eval(f),a,b,n).n(digits=6) r=rSum(lambda x: eval(f),a,b,n).n(digits=6) t=tSum(lambda x: eval(f),a,b,n).n(digits=6) e=tError(lambda x: eval(f),a,b,n).n(digits=6) print "l\t\tr\t\tt\t\te" print l,"\t",r,"\t",t,"\t",e 
       
l		r		t		e
-35.5000 	-47.5000 	-41.5000 	-6.00000
l		r		t		e
-35.5000 	-47.5000 	-41.5000 	-6.00000