Created
September 3, 2021 20:07
-
-
Save airicbear/8f87a4594d8ca4287a378818ecaa85d0 to your computer and use it in GitHub Desktop.
Riemann Sum (Midpoint)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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