链式钟摆
多个相连的摆锤依次摆动,展示能量传递与运动同步现象。
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()