lr_riemann.py

Created by tracy-pratt-1

Created on August 19, 2025

1.75 KB


from math import *
from cmath import *
from matplotlib.pyplot import *

# Input table of values
print("Compute a Riemann Sum from a")
print("table of value (separate")
print("values using commas)")
xs = [float(v) for v in input("Enter x-values: ").split(",")]
ys = [float(v) for v in input("Enter y-values: ").split(",")]

# Select a type of sum
print("Pick type of sum")
print("L (Left), R (Right), B (Both)")
print("*no graph provided for Both")
rtype = input("Riemann sum type: ").strip().upper()

# Function to compute sums
def riemann_sum(xs, ys, rtype):
    total = 0
    for i in range(len(xs)-1):
        dx = xs[i+1] - xs[i]
        if rtype == "L":
            height = ys[i]
        elif rtype == "R":
            height = ys[i+1]
        else:
            height = 0
        total += height * dx
    return total

# Case B (Both): compute & print values only
if rtype == "B":
    left = riemann_sum(xs, ys, "L")
    right = riemann_sum(xs, ys, "R")
    print("Left Riemann Sum:", left)
    print("Right Riemann Sum:", right)

else:
    # Single type chosen → compute + plot
    result = riemann_sum(xs, ys, rtype)
    print(rtype + " Riemann Sum:", result)

    # Plot
    xmin=int(min(xs)-2)
    xmax=int(max(xs)+2)
    padding=max(5,.25*(max(ys)-min(ys)))
    ymin=int(min(0, min(ys))-padding)
    ymax=int(max(0, max(ys))+padding)
    axis((xmin,xmax,ymin,ymax))
    scatter(xs, ys, color="red")
    plot(xs, ys, color="blue")
    text(xmin+.5,ymax-1,rtype + " Riemann Sum:"+ str(round(result,3)))

    # Draw rectangles
    for i in range(len(xs)-1):
        x0, x1 = xs[i], xs[i+1]
        dx = x1 - x0
        if rtype == "L":
            height = ys[i]
        elif rtype == "R":
            height = ys[i+1]
        bar(x0+dx/2, height,dx)

    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.