周期性方波-python演示

周期性方波-python演示

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# ================= 基本参数 =================
T = 2 * np.pi
w0 = 2 * np.pi / T

# 多周期时间轴
#num_periods = 3
num_periods = 6
t = np.linspace(-num_periods*np.pi, num_periods*np.pi, 40000)

# ================= 画布初始化 =================
fig, ax = plt.subplots(figsize=(10, 4.5))
line, = ax.plot([], [], lw=2)

ax.set_xlim(t[0], t[-1])
ax.set_ylim(-0.3, 1.3)
ax.set_xlabel("t")
ax.set_ylabel("x(t)")
ax.grid(True)

title = ax.set_title("")

# ================= 傅里叶合成函数 =================
def synthesize(N):
    x = np.zeros_like(t, dtype=complex)
    for k in range(-N, N + 1):
        if k == 0:
            ak = 0.5
        else:
            ak = np.sin(np.pi * k / 2) / (k * np.pi)
        x += ak * np.exp(1j * k * w0 * t)
    return x.real

# ================= 初始化帧 =================
def init():
    x0 = synthesize(1)
    line.set_data(t, x0)
    title.set_text("Periodic Square Wave Reconstruction (k = ±1)")
    return line, title

# ================= 动态更新 =================
def update(N):
    x = synthesize(N)
    line.set_data(t, x)
    title.set_text(f"Periodic Square Wave Reconstruction (k = ±{N})")
    return line, title

# ================= 动画 =================
ani = FuncAnimation(
    fig,
    update,
    frames=range(1, 101),   # N: 1 → 100
    init_func=init,
    interval=100,          # 每 0.1 秒
    blit=False,
    repeat=False
)

plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值