多个相连的摆锤依次摆动,展示能量传递与运动同步现象。

链式钟摆
多个相连的摆锤依次摆动,展示能量传递与运动同步现象。

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

# 链式钟摆参数
n_pendulums = 5
lengths = np.linspace(1, 2, n_pendulums)
masses = np.ones(n_pendulums)
g = 9.81
dt = 0.01
t_max = 20
t = np.arange(0, t_max, dt)

# 初始条件
theta0 = np.pi / 4 * np.ones(n_pendulums)
omega0 = np.zeros(n_pendulums)


# 运动方程
def pendulum_equations(y, t, lengths, masses, g):
    n = len(lengths)
    theta = y[:n]
    omega = y[n:]
    dydt = np.zeros(2 * n)
    dydt[:n] = omega

    for i in range(n):
        numerator = -g * np.sin(theta[i])
        for j in range(n):
            if i != j:
                numerator -= (masses[j] * lengths[j] * omega[j] ** 2 * np.sin(theta[i] - theta[j]) +
                              masses[j] * g * np.cos(theta[j]) * np.sin(theta[i] - theta[j])) / masses[i]
        dydt[n + i] = numerator / lengths[i]

    return dydt


# 数值求解
from scipy.integrate import odeint

y0 = np.concatenate((theta0, omega0))
sol = odeint(pendulum_equations, y0, t, args=(lengths, masses, g))
theta_sol = sol[:, :n_pendulums]

# 设置图形
fig, ax = plt.subplots()
ax.set_xlim(-2.5, 2.5)
ax.set_ylim(-2.5, 0.5)
lines = [ax.plot([], [], 'o-', lw=2)[0] for _ in range(n_pendulums)]


# 初始化函数
def init():
    for line in lines:
        line.set_data([], [])
    return lines


# 动画更新函数
def update(frame):
    for i in range(n_pendulums):
        x = lengths[i] * np.sin(theta_sol[frame, i])
        y = -lengths[i] * np.cos(theta_sol[frame, i])
        lines[i].set_data([0, x], [0, y])
    return lines


# 创建动画
ani = FuncAnimation(fig, update, frames=len(t), init_func=init, blit=True, interval=dt * 1000)

plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值