Python 基于积分原理计算定积分并可视化数值积分计算的动画过程


一、问题描述

有这样一个问题,如下所示:
请添加图片描述

∫ 0 1 x 3 + 1 = [ 1 4 x 4 + x ] 0 1 = 1.25 \int_{0}^{1} x^{3}+1=\left[\frac{1}{4} x^{4}+x\right]_{0}^{1}=1.25 01x3+1=[41x4+x]01=1.25


二、代码实现

1.  并基于积分原理计算  ∫ 0 1 x 3 + 1  的值  1. \text { 并基于积分原理计算 } \int_{0}^{1} x^{3}+1 \text { 的值 } 1. 并基于积分原理计算 01x3+1 的值 

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 的结果。

2.   可 视 化 积 分 的 动 画 过 程 2.\text { }可视化积分的动画过程 2. 

导入需要的依赖库:

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 通过路径连接绘制图像。

更新函数如下:

# 更新函数
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 启动动画:

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代码跑起来,如下所示:

在这里插入图片描述


补充学习:

猜你喜欢

转载自blog.csdn.net/fyfugoyfa/article/details/123509263