numint.py

Created by cesphoto

Created on July 27, 2023

1.28 KB

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()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.