from numpy import * def midpointn(f, a, b, n): h = (b - a)/n return h*sum( f(a+h/2+(arange(n))*h) ) def trapezoidaln(f, a, b, n): h = (b - a)/n return h*( (f(a) + f(b))/2 + sum( f(a+(arange(1,n))*h ) ) ) def simpsonn(f, a, b, n): h = (b - a)/(2*n) return h*(f(a) + f(b) + \ 2*sum( f(a+2*h*(arange(1,n))) ) + \ 4*sum( f(a+h+2*h*(arange(n)))))/3 midpointn(exp,0,1,10) print(trapezoidaln(exp,0,1,10)) print(trapezoidaln(lambda x: sin(x)/(1+x**2), 0, pi/2, 6)) print(simpsonn(exp,0,1,10)) print(simpsonn(lambda x: sin(x)/(1+x**2), 0, pi/2, 6)) def int_vals(n): l = (1/n)*sum(exp(arange(n)/n)) u = (1/n)*sum(exp(arange(1,n+1)/n)) l_err = abs(l-(exp(1)-1)) u_err = abs(u-(exp(1)-1)) return l, u, l_err, u_err [l, u, l_err, u_err]=int_vals(10) print(l) print(u) print(l_err) print(u_err) n = 1; l,u,l_err,u_err=int_vals(n) while l_err > 3*10**(-3): n = n+1 l,u,l_err,u_err=int_vals(n) print(n)