{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Mandelbrot set\n",
    "\n",
    "Compute the Mandelbrot fractal and plot it\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 30312 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from numpy import newaxis\n",
    "import warnings\n",
    "\n",
    "\n",
    "def compute_mandelbrot(N_max, some_threshold, nx, ny):\n",
    "    \"\"\"\n",
    "    计算 Mandelbrot 集合的布尔数组。\n",
    "\n",
    "    参数\n",
    "    ----\n",
    "    N_max : int\n",
    "        最大迭代次数。\n",
    "    some_threshold : float\n",
    "        模长阈值，用于判断点是否属于 Mandelbrot 集。\n",
    "    nx, ny : int\n",
    "        图像在 x、y 方向的像素个数。\n",
    "\n",
    "    返回\n",
    "    ----\n",
    "    mandelbrot_set : 二维 bool 数组 (nx, ny)\n",
    "        True 表示对应复数 c 属于 Mandelbrot 集。\n",
    "    \"\"\"\n",
    "\n",
    "    # 1. 构造复平面网格\n",
    "    x = np.linspace(-2, 1, nx)          # 实轴范围 [-2, 1]\n",
    "    y = np.linspace(-1.5, 1.5, ny)      # 虚轴范围 [-1.5, 1.5]\n",
    "    c = x[:, np.newaxis] + 1j * y[np.newaxis, :]   # 广播成 (nx, ny) 复数矩阵\n",
    "\n",
    "    # 2. 初始化 z，与 c 同形\n",
    "    z = c.copy()\n",
    "\n",
    "    # 3. 迭代：z_{n+1} = z_n^2 + c\n",
    "    #    屏蔽运行时警告（溢出/无效值在集合外部必然出现）\n",
    "    with warnings.catch_warnings():\n",
    "        warnings.simplefilter(\"ignore\")\n",
    "        for _ in range(N_max):\n",
    "            z = z**2 + c\n",
    "\n",
    "    # 4. 根据最终模长判断是否在集合内\n",
    "    mandelbrot_set = abs(z) < some_threshold\n",
    "    return mandelbrot_set\n",
    "\n",
    "\n",
    "# 5. 生成 601×401 像素的 Mandelbrot 集合\n",
    "mandelbrot_set = compute_mandelbrot(N_max=50, some_threshold=50.0,\n",
    "                                    nx=601, ny=401)\n",
    "\n",
    "# 6. 绘制：转置使 y 轴竖直，extent 设定坐标轴范围\n",
    "plt.imshow(mandelbrot_set.T, extent=(-2, 1, -1.5, 1.5))\n",
    "\n",
    "# 7. 使用灰度色阶（黑色=集合内，白色=集合外）\n",
    "plt.gray()\n",
    "\n",
    "# 8. 显示图形\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
}
