Skip to content

Instantly share code, notes, and snippets.

@airicbear
Created September 3, 2021 20:07
Show Gist options
  • Save airicbear/8f87a4594d8ca4287a378818ecaa85d0 to your computer and use it in GitHub Desktop.
Save airicbear/8f87a4594d8ca4287a378818ecaa85d0 to your computer and use it in GitHub Desktop.
Riemann Sum (Midpoint)
def rsm(f, x0, xn, n):
"""Approximates integral using Riemann sum of the midpoint.
Takes the function f(x), bounds a and b, and number of partitions, n as arguments."""
dx = (xn - x0) / n
return [f(x0 + i*dx) for i in range(0,n)]
x0 = 0
xn = 2
n = 4
dx = (xn - x0) / n
xs = np.linspace(x0, xn, 100)
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
ax.plot(xs, [x**3 for x in xs])
for i in range(0, n):
x = x0 + i*dx + dx/2
ax.scatter(x, x**3, color='r')
ax.add_patch(Rectangle((x-dx/2, 0), dx, x**3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment