python - 如何绘制给定积分的面积?

标签 python function matplotlib

我有以下脚本:

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))

现在,我想绘制 ab 描述的范围内的 f(x) 曲线,下面有积分区域它,所以我可以得到这样的东西:

enter image description here

我知道如何完成第一部分,即在特定范围内绘制 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()

enter image description here

关于python - 如何绘制给定积分的面积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27360946/

相关文章:

python - 为什么 django 的默认身份验证后端在引发 UserModel.DoesNotExist 异常后调用 set_password?

python - 如何在 python 中从 HDFS sequencefile 加载数据

python - 尝试使用 python 访问共享点列表

matplotlib 中的动画与分散和使用 set_offsets : Autoscale of figure is not working

python - 在绘图上标记 python 数据点

python - Matplotlib 在绘图中写入 '±'

python - 向 locals() 显式添加东西有多糟糕?

postgresql - 如何从函数(存储过程)中获取 INPUT 值?与 golang

javascript - 只需使用一次 console.log 函数

c - 你如何在c中使用 float 作为指数