Pythonは、積分の原理に基づいて定積分を計算し、数値積分計算のアニメーションプロセスを視覚化します


1.問題の説明

次のような問題があります。
画像の説明を追加してください

∫01x3 + 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.2501バツ3+1=[41バツ4+x ]01=1 2 5


第二に、コードの実装

1.そして積分の原理に基づいて∫01x3+1の値を計算します1.\text{そして積分の原理に基づいて計算します}\int_ {0} ^ {1} x ^ {3} + 1 \text{値}1.そして統合の原則に基づいて計算されます  01バツ3+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はパスの生成に使用され、patchはパス接続を介して画像を描画するために使用されます。

更新機能は次のとおりです。

# 更新函数
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]

FuncAnimationを使用してfigオブジェクトを初期化し、アニメーションを開始します。

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