lSum Practice with range()

3151 days ago by MATH4H2012

a=0 b=5 n=10 h=(b-a)/n f(x)=x^2 sum([f(a+i*h)*h for i in range(n)]).n() 
       
range(n) 
       
[i for i in range(n)] 
       
[i*h for i in range(n)] 
       

__SAGE__
Traceback (click to the left of this block for traceback)
...
__SAGE__
__SAGE__
Traceback (most recent call last):
  File "c_lib.pyx", line 68, in sage.ext.c_lib.sage_python_check_interrupt (sage/ext/c_lib.c:736)
KeyboardInterrupt
__SAGE__
[a+i*h for i in range(n)] 
       
[f(a+i*h) for i in range(n)] 
       
[f(a+i*h)*h for i in range(n)] 
       
sum([f(a+i*h)*h for i in range(n)]) 
       
sum([f(a+i*h)*h for i in range(n)]).n() 
       
def lSum(a,b,n,f): h=(b-a)/n return sum([f(a+i*h)*h for i in range(n)]).n() f="x**2" show(lSum(0,5,10,lambda x: eval(f))) print "n\tlSum" for n in range(5): print "10^",n,"\t",lSum(0,5,10^n,lambda x: eval(f)) 
       

n	lSum
10^ 0 	0.000000000000000
10^ 1 	35.6250000000000
10^ 2 	41.0437500000000
10^ 3 	41.6041875000000
10^ 4 	41.6604168750000
n	lSum
10^ 0 	0.000000000000000
10^ 1 	35.6250000000000
10^ 2 	41.0437500000000
10^ 3 	41.6041875000000
10^ 4 	41.6604168750000
@interact def _(a=0, b=5, g = x, n=(0,100,1)): f(x)=g Q=plot(f,(x,a,b)) RP=plot(0,(x,a,b)) h=(b-a)/n for j in range(n): P=plot(f(a+j*h),(x,a+j*h,a+(j+1)*h),fill=True) NP=P+RP RP=NP show(RP+Q,ticks=[[a,a+h..b],None]) k=var('k') html("The Riemann sum approximating $\int_{%s}^{%s} %s \, dx$ adds up to $%s$."%(latex(a),latex(b),latex(g),sum(h*(f(a+k*h)),k,1,n))) 
       

Click to the left again to hide and once more to show the dynamic interactive window

@interact def _(a=1, b=2, g = 4-x^2, n=(1,10,1)): f(x)=g Q=plot(f,(x,a,b)) RP=plot(0,(x,a,b)) h=(b-a)/n for j in range(n): P=plot(f(a+j*h),(x,a+j*h,a+(j+1)*h),fill=True) NP=P+RP RP=NP show(RP+Q,ticks=[[a,a+h..b],None]) k=var('k') html("The Riemann sum approximating $\int_{%s}^{%s} %s \, dx$ adds up to $%s$."%(latex(a),latex(b),latex(g),sum(h*(f(a+k*h)),k,1,n))) 
       

Click to the left again to hide and once more to show the dynamic interactive window