Calculus UNIT507: Riemann Sums with Graphical Output!

2405 days ago by MATH4R2013

#1) LSUM! f="exp(-x)" a=1 b=5 n=8 def lSum(f,a,b,n): p=Graphics() h=(b-a)/n l=sum([f(a+i*h)*h for i in range(n)]) for i in range(n): x=a+i*h y=f(a+i*h) p+=polygon([(x,0),(x,y),(x+h,y),(x+h,0)],fill=False) p+=plot(f,a,b,color='red',fill=True) p.show(aspect_ratio=1) return l print "l=",lSum(lambda x: eval(f),a,b,n).n(digits=6) 
       
l= 
0.458919
l= 
0.458919
#2) RSUM! f="exp(-x)" a=1 b=5 n=8 def rSum(f,a,b,n): p=Graphics() h=(b-a)/n r=sum([f(a+i*h)*h for i in range(n)])-f(a)*h+f(b)*h for i in range(n): x=a+i*h y=f(a+(i+1)*h) p+=polygon([(x,0),(x,y),(x+h,y),(x+h,0)],fill=False) p+=plot(f,a,b,color='red',fill=True) p.show(aspect_ratio=1) return r print "r=",rSum(lambda x: eval(f),a,b,n).n(digits=6) 
       
r= 
0.278349
r= 
0.278349
#3) TRAP! f="exp(-x)" a=0 b=5 n=4 def tSum(f,a,b,n): p=Graphics() h=(b-a)/n l=sum([f(a+i*h)*h for i in range(n)]) r=sum([f(a+i*h)*h for i in range(n)])-f(a)*h+f(b)*h t=((r+l)/2).n(digits=6) e=((r-l)/2).n(digits=6) for i in range(n): x=a+i*h y1=f(a+i*h) y2=f(a+(i+1)*h) p+=polygon([(x,0),(x,y1),(x+h,y2),(x+h,0)],fill=False) p+=plot(f,a,b,color='red',fill=True) p.show(aspect_ratio=1) return [t,e] print "[t,e]=",tSum(lambda x: eval(f),a,b,n) 
       
[t,e]= 
[1.11935, -0.620789]
[t,e]= 
[1.11935, -0.620789]