使用matplotlib说明Trapzeium / Simpson规则

时间:2016-12-02 20:21:48

标签: python matplotlib

绘制了多个函数,现在需要说明实际面积/积分与近似面积/积分结果之间的误差(使用梯形或辛普森统计量计算)。远离这里/其他地方的研究,目前只绘制一个三角形 - 我认为位置不正确。有什么输入?提前谢谢。

N.B。如果需要,计算中早先计算了精确值和近似积分值。

import numpy as np
import matplotlib.pyplot as plt

def f1(x):
    return np.exp(-4*x)*np.cos(6*np.pi*x)

x = np.linspace(0, 1, 1500)
fig = plt.figure()
ax1 = fig.add_subplot(322)
xstep = np.arange(0,2)
ax1.fill_between(f1(xstep), 0, xstep, facecolor='white')  # Trapezium
ax1.plot(x, f1(x),'r-')  # Function

1 个答案:

答案 0 :(得分:0)

是的,三角形位于错误的位置。

问题在于fill_between - 参数应为RuntimeException,其中(x1, y1, y2)是确定“between”之间的值。如果你在代码中增加了三角形的数量,你就会看到发生了什么 - 交换了x和y轴。如果更改,则三角形点将处于正确的值。

这是我用来检查的代码。请注意,我添加了一个变量n_steps(使其更容易测试):

y1

结果如下:

graph result

y = 0处的黑线由import numpy as np import matplotlib.pyplot as plt def f1(x): return np.exp(-4*x)*np.cos(6*np.pi*x) # parameters for trapezoid rule n_steps = 6 # set up figure fig = plt.figure() ax1 = fig.add_subplot(111)#(322) # range for function x = np.linspace(0, 1, 1500) xstep = np.linspace(0, 1, n_steps) # plot the trapezoid ax1.fill_between(xstep, 0, f1(xstep), facecolor='white') # plot the function ax1.plot(x, f1(x),'r-') # Function plt.show() 生成。我建议在这些点上放置垂直线,以便更清楚地说明计算是如何完成的。您可以在绘制梯形后添加代码,但在绘制函数之前:

fill_between

导致:

graph with vertical lines