Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168733
Image: ubuntu2004

Trapezoidal Rule

Approximation of abf(x)dx\int_a^b f(x) {\rm d}x for x[a,b]x \in [a, b] using the trapezoid rule.

i=0n1f(xi)+f(xi+Δx)2Δx\sum_{i=0}^{n-1} \frac{f(x_i)+f(x_i+\Delta_x)}{2} \cdot \Delta_x

for xi=a+iΔxx_i = a + i \cdot \Delta_x with Δx=ban\Delta_x = \frac{b-a}{n} and nN+n \in \mathbb{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\int_a^b f(x) {\rm d} x with x[a,b]x \in [a,b] with

f(a) Δx2 +i=1n1f(xi)Δx +f(b) Δx2\frac{f(a) \cdot  \Delta_x}{2}  + \sum_{i=1}^{n-1} f(x_i) \cdot \Delta_x  + \frac{f(b) \cdot  \Delta_x}{2}

for xi=a+iΔxx_i = a+ i \cdot \Delta_x with Δx=b1n\Delta_x = \frac{b-1}{n} and nN+n \in \mathbb{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]