栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

文章目录

一、问题描述二、代码实现

1.  并基于积分原理计算  ∫ 0 1 x 3 + 1  的值  1. text { 并基于积分原理计算 } int_{0}^{1} x^{3}+1 text { 的值 } 1. 并基于积分原理计算 ∫01​x3+1 的值  2.   可 视 化 积 分 的 动 画 过 程 2.text { }可视化积分的动画过程 2. 可视化积分的动画过程


一、问题描述

有这样一个问题,如下所示:

∫ 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}+xright]_{0}^{1}=1.25 ∫01​x3+1=[41​x4+x]01​=1.25


二、代码实现 1.  并基于积分原理计算  ∫ 0 1 x 3 + 1  的值  1. text { 并基于积分原理计算 } int_{0}^{1} x^{3}+1 text { 的值 } 1. 并基于积分原理计算 ∫01​x3+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代码跑起来,如下所示:


补充学习:

https://blog.csdn.net/lhys666/article/details/123451524https://blog.csdn.net/lhys666/article/details/122776649

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/768087.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号