比较非线性与小角度单摆
积分明确声明的理想模型,从过零点估计周期,并审计能量守恒。
目标与运行方法
本课适合具备 Python 基础的本科生。先阅读每一步的方法与图注,再修改参数。AI 练习为可选部分,不需要 AI 账号即可完成核心课程。数据写在 notebook metadata 中,不需要另下载数据文件。请保持 notebook 已保存到当前工作文件夹。
学习任务是理解本课的研究问题、执行透明的计算、校验结果,并说明结论的边界。
环境与参数
from pathlib import Path
import base64, gzip, hashlib, json, platform
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display, HTML
from scipy.integrate import solve_ivp
from IPython.display import display as _display
def display(value):
if isinstance(value,pd.DataFrame):
table=value.to_html(max_rows=12,escape=True)
style="<style>.vibeit-readable-table{max-width:100%;overflow-x:auto}.vibeit-readable-table table{width:max-content;max-width:none;border-collapse:collapse}.vibeit-readable-table td,.vibeit-readable-table th{white-space:nowrap!important;word-break:normal!important;overflow-wrap:normal!important}</style>"
return _display(HTML(style+'<div class="vibeit-readable-table">'+table+'</div>'))
return _display(value)
RECIPE_ID='ph01-pendulum'
OUTPUT_DIR=Path.cwd()/"results"/RECIPE_ID
plt.rcParams.update({"figure.dpi":120,"font.size":10,"axes.spines.top":False,"axes.spines.right":False,
"axes.prop_cycle":plt.cycler(color=["#18785f","#416aa6","#bc6541","#9974a5"])})
print("Python:",platform.python_version(),"; NumPy:",np.__version__,"; Pandas:",pd.__version__)
print("Working folder:",Path.cwd())
print("Core data mode: embedded snapshot; no network requests")
Python: 3.13.13 ; NumPy: 2.5.3 ; Pandas: 3.0.6 Working folder: /Users/zhiluo/Developer/vibeit-cookbook/cookbook/downloads Core data mode: embedded snapshot; no network requests
读取内嵌快照
def load_snapshot(recipe_id, expected_sha256, snapshot_key):
"""Read embedded data from this notebook, including a renamed copy."""
for path in sorted(Path.cwd().glob("*.ipynb")):
try:
notebook = json.loads(path.read_text(encoding="utf-8"))
metadata = notebook.get("metadata", {}).get("vibeit_cookbook", {})
blob = metadata.get("snapshots", {}).get(snapshot_key)
if metadata.get("recipe_id") != recipe_id or not blob:
continue
if blob.get("sha256") != expected_sha256:
continue
raw = gzip.decompress(base64.b64decode(blob["gzip_base64"], validate=True))
if hashlib.sha256(raw).hexdigest() != expected_sha256:
raise ValueError("Embedded snapshot checksum mismatch: " + snapshot_key)
return json.loads(raw)
except (OSError, json.JSONDecodeError):
continue
raise FileNotFoundError(
"Save/open the complete .ipynb in the active working folder. "
"The embedded snapshot could not be located for " + recipe_id)
SNAPSHOT_HASHES={'models': '48fd2e6e706650fe2ee0c0ad80b6d794a546a1dec78dd9d370ac09db3cc3adbf', 'constants': '2533802a1a546c612d06ba2e931e4f32a418be854c75a5e9c327ff57d5b56126'}
def snapshot(key):
return load_snapshot(RECIPE_ID,SNAPSHOT_HASHES[key],key)
print("Embedded snapshots:",list(SNAPSHOT_HASHES))
Embedded snapshots: ['models', 'constants']
方法函数
def pendulum_solution(length_m,gravity,angle_deg,duration_s=20,samples=2001):
"""Nonlinear ideal pendulum; energy is per unit mass in J/kg."""
if length_m<=0 or gravity<=0 or not 0<abs(angle_deg)<180 or duration_s<=0 or samples<3:
raise ValueError('Use positive length/gravity/time and a nonzero angle below 180 degrees')
def dynamics(t,state):return [state[1],-gravity/length_m*np.sin(state[0])]
t=np.linspace(0,duration_s,samples)
solved=solve_ivp(dynamics,[0,duration_s],[np.deg2rad(angle_deg),0],t_eval=t,rtol=1e-9,atol=1e-11)
if not solved.success:raise RuntimeError(solved.message)
theta,omega=solved.y;energy=.5*length_m**2*omega**2+gravity*length_m*(1-np.cos(theta))
indices=np.flatnonzero((theta[:-1]>0)&(theta[1:]<=0))
crossings=[t[j]-theta[j]*(t[j+1]-t[j])/(theta[j+1]-theta[j]) for j in indices]
period=float(np.mean(np.diff(crossings))) if len(crossings)>1 else float('nan')
return dict(t=t,theta=theta,omega=omega,energy_per_mass=energy,period_s=period)
print("Method ready: pendulum_solution")
Method ready: pendulum_solution
数据与模型边界
单摆、振子、抛体和温度轨迹是明确声明的数值模型,不是实验室测量。使用的 g0 为约定标准重力加速度。GW150914 使用真实冻结应变和已发表事件时间;滤波曲线不是独立的显著性或源参数分析。黑体曲线假定理想辐射体。
分步分析
1. 设定单位并比较三个初始角度
取一米摆长及标准 g0。求解器状态为弧度角度和 rad/s 角速度。小角度近似使用 sin(theta)≈theta,其周期不依赖初始振幅。
parameters=snapshot("models")["pendulum"];gravity=snapshot("constants")["constants"]["g_0"]["value"]
length=parameters["length_m"];angles=parameters["angles_deg"]
solutions={angle:pendulum_solution(length,gravity,angle,parameters["duration_s"]) for angle in angles}
linear_period=2*np.pi*np.sqrt(length/gravity)
print("Length (m):",length,"; standard g0 (m/s²):",gravity,"; small-angle period (s):",linear_period)
fig,ax=plt.subplots(figsize=(9,4));large=solutions[90]
ax.plot(large["t"],np.rad2deg(large["theta"]),label="Nonlinear 90° initial angle")
ax.plot(large["t"],90*np.cos(np.sqrt(gravity/length)*large["t"]),"--",label="Small-angle approximation")
ax.set(xlabel="Model time (s)",ylabel="Angle (degrees)",title="Amplitude changes the nonlinear timing");ax.legend();plt.tight_layout();plt.show()
Length (m): 1.0 ; standard g0 (m/s²): 9.80665 ; small-angle period (s): 2.0064092925890407
2. 由实际过零点估计周期
对保存样本之间的重复向下过零点做线性插值。周期估计包含插值与求解误差,也需要足够周期。与线性周期的差别描述模型近似误差。
periods=np.array([solutions[a]["period_s"] for a in angles])
display(pd.DataFrame({"initial_angle_deg":angles,"nonlinear_period_s":periods,"small_angle_period_s":linear_period,"relative_difference":periods/linear_period-1}))
fig,ax=plt.subplots(figsize=(7,4));ax.plot(angles,periods,"o-",label="Zero-crossing estimate")
ax.axhline(linear_period,color="gray",linestyle="--",label="Small-angle prediction")
ax.set(xlabel="Initial angle magnitude (degrees)",ylabel="Period (s)",title="Nonlinear period depends on amplitude");ax.legend();plt.tight_layout();plt.show()
| initial_angle_deg | nonlinear_period_s | small_angle_period_s | relative_difference | |
|---|---|---|---|---|
| 0 | 5 | 2.007365 | 2.006409 | 0.000476 |
| 1 | 30 | 2.041338 | 2.006409 | 0.017409 |
| 2 | 90 | 2.368246 | 2.006409 | 0.180341 |
3. 审计单位质量的守恒能量
单位质量能量为 ½L²ω²+gL(1−cos(theta)),单位 J/kg。图上展示相对初值的漂移。理想模型能量守恒,微小变化描述数值积分,而不是真实摩擦。
fig,ax=plt.subplots(figsize=(9,4))
for angle,solution in solutions.items():
energy=solution["energy_per_mass"];ax.plot(solution["t"],(energy-energy[0])/energy[0],label=f"{angle}°")
ax.set(xlabel="Model time (s)",ylabel="Relative energy drift",title="Numerical energy audit");ax.legend();plt.tight_layout();plt.show()
4. 检查极限模型并导出
五度解应接近小角度周期。在此理想范围内,更大角度具有更长周期。转用于其他系统之前,检查有限状态值与能量漂移。
assert abs(periods[0]/linear_period-1)<.002 and np.all(np.diff(periods)>0)
OUTPUT_DIR.mkdir(parents=True,exist_ok=True)
for angle,solution in solutions.items():
energy=solution["energy_per_mass"];assert np.max(np.abs((energy-energy[0])/energy[0]))<1e-6
pd.DataFrame({"time_s":solution["t"],"angle_rad":solution["theta"],"angular_velocity_rad_per_s":solution["omega"],"energy_J_per_kg":energy}).to_csv(OUTPUT_DIR/f"pendulum-{angle}-degrees.csv",index=False)
print("Limiting-period and energy checks passed; exports:",OUTPUT_DIR)
Limiting-period and energy checks passed; exports: /Users/zhiluo/Developer/vibeit-cookbook/cookbook/downloads/results/ph01-pendulum
自主练习与参考答案
- 解释九十度周期为何不同于小角度周期。
- 解释相对能量漂移曲线。
参考解释。 非线性回复加速度使用 sin(theta),大角度计时因此不同。相对漂移是理想守恒模型的数值审计,不是实测摩擦。
先保留当前 notebook 副本,再修改参数。把新图与原图一起比较,并记录改变了哪些输入、哪些计算和哪些结论。
可选的 AI 编程练习
提示词 1
仅用 NumPy、SciPy、Matplotlib 加入六十度,保留过零点和能量校验。
提示词 2
使用同样的包缩小求解容差,比较能量漂移,不改物理参数。
人工验收。 周期有限,小角度仍接近线性值,相对能量漂移受限。
检查修改后的源代码,再手动运行受影响单元及后续校验。要求助手解释修改的目的、使用的包和数据来源,并用实际输出核对解释。
可选联网扩展
RUN_ONLINE_UPDATE=False
if RUN_ONLINE_UPDATE:
import requests
try:
response=requests.get('https://physics.nist.gov/cuu/Constants/',timeout=20)
response.raise_for_status()
print("Source:",response.url)
print(response.text[:700])
except requests.RequestException as error:
print("Online extension unavailable:",type(error).__name__,str(error)[:160])
else:
print("Online extension skipped; embedded core data unchanged")
Online extension skipped; embedded core data unchanged
来源、快照与下一步
NIST CODATA physical constants — NIST public reference data; credit NIST/CODATA; retrieved 2026-10-09. SHA-256
77fb90e66c40db3e6eb16630bc9c88e4c7c8beddbe5e71be406f2f26e3f67e67. Preserve official ASCII table; extract seven explicitly named SI constants and their units.IAPWS saturation reference release — IAPWS SR1-86(1992): unrestricted publication allowed in all countries (cover page); retrieved 2026-10-09. SHA-256
a10d38d73339b0713c86cfac88f9adcba137202167ccdfa1cd58238c438361d7. Reference equations and numerical coefficients transcribed from release pages 2–3; pedagogical model values are not new experiments.Authored numerical teaching model parameters — Original teaching parameters/code MIT; reference equation coefficients attributed to IAPWS SR1-86(1992); retrieved 2026-10-09. SHA-256
4350c4305a83c772fa295a8be0ef86a247f2bfaae930a081720d3cd0c753abe0. Declared parameters and seed; generated trajectories and calibration observations must be labelled simulated.
下一步。 在保留本课的数据检查、参数记录和结果校验之后,将相同方法用于自己的公开或已获授权数据。记录研究设计与方法限制,不把示例结果当成新实验的验证。完整数据许可与生成说明见 cookbook 网页。