文章目录
一、问题描述
二、代码实现
代码语言:javascript复制def func(x):
return x ** 3 1
down = 0
upper = 1
interval = np.linspace(start=down, stop=upper, num=100)
result = 0
for i in range(0, len(interval) - 1):
left = interval[i]
right = interval[i 1]
width = right - left
height = func(left)
area = width * height
result = area
print(f"{result:.2f}")
结果如下:
取 50 个矩形计算数值积分的时候,已经可以得到 1.24 的结果。
导入需要的依赖库:
代码语言:javascript复制import numpy as np
import matplotlib.path as path
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from IPython.display import HTML
from matplotlib.animation import FuncAnimation
import warnings
warnings.filterwarnings("ignore")
其中,numpy 用来生成点数据,path 是用来生成路径,patches 通过路径连接绘制图像。
更新函数如下:
代码语言:javascript复制# 更新函数
def update(frame):
global points, verts, codes
# x轴间隔距离 每个bin
dx = (interval[1] - interval[0]) / bins
points = np.append(points, [[frame, func(frame)]], axis=0)
verts = np.append(verts,
[[frame, 0], [frame, func(frame)], [frame dx, func(frame)], [frame dx, 0]], axis=0)
ln[0].set_data(list(zip(*points)))
codes.extend([path.Path.MOVETO] [path.Path.LINETO] * 3)
barpath = path.Path(verts, codes)
patch = patches.PathPatch(barpath,
facecolor='blue',
edgecolor='yellow', alpha=0.6)
ax.add_patch(patch)
return patch, ln[0]
初始化 fig 对象与 FuncAnimation 启动动画:
代码语言:javascript复制fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
ax.axis(interval)
global points, verts, codes
codes = []
verts = np.empty((0, 2), np.float64)
points = np.empty((0, 2), np.float64)
plt.rcParams['font.sans-serif'] = ['Times New Roman']
plt.rcParams['axes.unicode_minus'] = False
ln = plt.plot([], [], 'ro')
# 设置坐标轴刻度标签的大小
plt.tick_params(axis='x', direction='out',
labelsize=12, length=3.6)
plt.tick_params(axis='y', direction='out',
labelsize=12, length=3.6)
# x y 轴标签 标题 字体设置
plt.xlabel("x",
fontdict={"size": 16, "weight": "bold", "color": "black"})
plt.ylabel("f(x)",
fontdict={"size": 16, "weight": "bold", "color": "black"}
)
plt.grid(alpha=0.48, ls=":")
# FuncAnimation动画 传入fig对象、更新函数 frames
anim = FuncAnimation(fig, update,
frames=np.linspace(*interval[:2], bins),
)
Python代码跑起来,如下所示: