| Download
All published worksheets from http://sagenb.org
Project: sagenb.org published worksheets
Views: 168733Image: ubuntu2004
Trapezoidal Rule
Approximation of ∫abf(x)dx for x∈[a,b] using the trapezoid rule.
i=0∑n−12f(xi)+f(xi+Δx)⋅Δx
for xi=a+i⋅Δx with Δx=nb−a and n∈N+
%auto # the function we are integrating var('x') f(x) = 1/2 * x^2 - 2*x + 1 def next_hue(dx): """ generator object for repetitive calls in the rgbcolor argument """ x = 0 while 1: if x > 1: x = 0 yield hue(x, 0.3) x += dx
%auto @interact def _(ab=range_slider(-4,10,0.1,(-2,6),'[a, b]'), dx=slider(0.1,3,0.1,1,'dx')): a, b = ab xvals = srange(a,b,dx, include_endpoint=True) fx = [f(x) for x in xvals] fg = plot(f, (x,a,b)) pts = point2d(zip(xvals,fx), rgbcolor='#ff3030', pointsize=30) lines = [([i,0], [i,f(i)], [i+dx, f(i+dx)], [i+dx, 0]) for i in xvals[0:-1]] nh = next_hue(1.0/len(xvals)) areas = sum(map(lambda p : polygon(p, rgbcolor=nh.next()), lines)) show(fg + areas + pts) areas = [ ( f(i) + f(i+dx) )/2 for i in xvals[0:-1]] print 'approximation: %s' % float(dx * sum(areas)) print 'numerical_integral: %s' % numerical_integral(f, a, b)[0]
Rectangle Rule
Approximation of ∫abf(x)dx with x∈[a,b] with
2f(a)⋅ Δx +∑i=1n−1f(xi)⋅Δx +2f(b)⋅ Δx
for xi=a+i⋅Δx with Δx=nb−1 and n∈N+
%auto @interact def _(ab=range_slider(-4,10,0.1,(-2,6),'[a, b]'), dx=slider(0.1,3,0.1,0.5,'dx')): a, b = ab xvals = srange(a,b,dx, include_endpoint=True) fx = [f(x) for x in xvals] fg = plot(f, (x,a,b)) pts = point2d(zip(xvals,fx), rgbcolor='#ff3030', pointsize=30) #lines = [([i,0], [i,f(i)], [i+dx, f(i+dx)], [i+dx, 0]) for i in xvals[0:-1]] lines = [([xvals[0], 0], [xvals[0], f(xvals[0])], [xvals[0] + dx/2, f(xvals[0])], [xvals[0] + dx/2, 0])] for i in xvals[1:-1]: x1, x2 = i-dx/2, i+dx/2 lines.append(([x1,0], [x1, f(i)], [x2, f(i)], [x2, 0])) x1, x2 = xvals[-1]-dx/2, xvals[-1] lines.append(([x1,0], [x1, f(x2)], [x2, f(x2)], [x2, 0])) nh = next_hue(1.0/len(xvals)) areas = sum(map(lambda p : polygon(p, rgbcolor=nh.next()), lines)) show(fg + areas + pts) areas = [f(i) for i in xvals[1:-1]] areas.append(f(xvals[0]) / 2) areas.append(f(xvals[-1]) / 2) print 'approximation: %s ' % float(dx * sum(areas)) print 'numerical_integral: %s' % numerical_integral(f, a, b)[0]