{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Random walk exercise\n",
    "\n",
    "Plot distance as a function of time for a random walk\n",
    "together with the theoretical result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 18512 characters]",
      "text/plain": [
       "<Figure size 400x300 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# 参数设定：1000 条随机行走轨迹，每条 200 步\n",
    "n_stories = 1000\n",
    "t_max = 200\n",
    "\n",
    "# 时间轴 [0, 1, 2, ..., 199]\n",
    "t = np.arange(t_max)\n",
    "\n",
    "# 生成每一步：randint(0,2) 返回 0/1，映射到 -1/+1\n",
    "rng = np.random.default_rng()\n",
    "steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1\n",
    "\n",
    "# 沿每条轨迹（axis=1）累加步长，得到各时刻的位置\n",
    "positions = np.cumsum(steps, axis=1)\n",
    "\n",
    "# 计算均方位移：先平方再按轨迹求平均\n",
    "sq_distance = positions**2\n",
    "mean_sq_distance = np.mean(sq_distance, axis=0)\n",
    "\n",
    "# 作图：绿色点线=模拟结果 ⟨x²⟩^(1/2)；黄色直线=理论 √(t)\n",
    "plt.figure(figsize=(4, 3))\n",
    "plt.plot(t, np.sqrt(mean_sq_distance), \"g.\", t, np.sqrt(t), \"y-\")\n",
    "plt.xlabel(r\"$t$\")\n",
    "plt.ylabel(r\"$\\sqrt{\\langle (\\delta x)^2 \\rangle}$\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
