Graphical and numerical integration with Riemann sums. Left, center, right, and trapezoid.
from math import * from matplotlib.pyplot import * #Define the function to integrate def f(x): return x**2 def run(): print("Plot Parameters") print("----------------------") a = float(input('xmin= ')) b = float(input('xmax= ')) c = float(input('ymin= ')) d = float(input('ymax= ')) print() print("Integration Parameters") print("----------------------") print("Type: 1: Left") print(" 2: Center") print(" 3: Right") print(" 4: Trapezoid") print() t = input("Type: ") if (t == "1") or (t == "4"): r=0 elif t == "2": r=1 else: r=0.5 xa = float(input('a= ')) xb = float(input('b= ')) n = int(input('n= ')) dx = (xb-xa)/n x = [a+i*(b-a)/50 for i in range(51)] y = [f(i) for i in x] if t == "4": area = (f(xa)+f(xb)+2*sum(f(xa+i*dx) for i in range(1,n)))*dx/2 else: xs = [xa+(i+r)*dx for i in range(n)] ys = [f(i) for i in xs] area = sum(ys)*dx text(a,d," Area= "+str(area)) axis((a,b,c,d)) plot(x,y,'blue') grid() if t == "4": for i in range(n): plot((i*dx+xa,i*dx+xa,(i+1)*dx+xa,(i+1)*dx+xa),(0,f(i*dx+xa),f((i+1)*dx+xa),0),'red') else: for i in range(n): plot((i*dx+xa,i*dx+xa,(i+1)*dx+xa,(i+1)*dx+xa),(0,f((i+r)*dx+xa),f((i+r)*dx+xa),0),'red') show()