我有以下脚本:
import numpy as np
def f(x):
return x**2 + 3
def integration(a, b, n):
dx = (b - a) / n
integration = 0
for i in np.arange(1, n + 1):
integration += f(a + i * dx)
integration *= dx
return integration
print(integration (0, 5, 10000))
现在,我想绘制 a
和 b
描述的范围内的 f(x)
曲线,下面有积分区域它,所以我可以得到这样的东西:
我知道如何完成第一部分,即在特定范围内绘制 f(x)
曲线:
import matplotlib.pylab as pl
x = np.linspace(0, 5, 10000)
def f(x):
return x**2 + 3
pl.plot(x, f(x))
pl.xlim([-1, 6])
pl.show()
...但我缺少其余的。我将不胜感激您的帮助。
最佳答案
感谢@Evert评论,这里是一个可行的解决方案:
'''
According to the rectangle rule.
'''
import numpy as np
import matplotlib.pylab as pl
from matplotlib.patches import Polygon
# Function definition.
def f(x):
return x ** 2 + 3
# Integration calculation.
def integration(a, b, n):
dx = (b - a) / n
integration = 0
for i in np.arange(1, n + 1):
integration += f(a + i * dx)
integration *= dx
return integration
# Define integral limits.
a, b = 0, 5
# Define x and y arrays.
x = np.linspace(0, 10, 10000)
y = f(x)
# Plot x and y.
fig, ax = pl.subplots()
pl.plot(x, y, 'b', linewidth = 2)
pl.xlim(xmin = -1, xmax = 11)
pl.ylim(ymin = 0)
# Shade area of the integration beneath the f(x) curve.
ix = np.linspace(a, b, 10000)
iy = f(ix)
verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]
poly = Polygon(verts, facecolor = '0.9', edgecolor = '0.5')
ax.add_patch(poly)
# Print equation text.
pl.text(0.5 * (a + b), 60, r"$\int_{a}^{b}f(x)dx=%.2f$" %integration(a, b, 10000),
horizontalalignment = 'center', fontsize = 20)
# Add x and y axes labels.
pl.figtext(0.9, 0.05, '$x$')
pl.figtext(0.1, 0.9, '$y$')
# Remove right and top plot delimeter lines.
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
# Add a and b ticks on x axis.
ax.set_xticks((a, b))
ax.set_xticklabels(('$a=%d$' %a, '$b=%d$' %b))
ax.set_yticks([])
# Show the plot.
pl.show()
关于python - 如何绘制给定积分的面积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27360946/