{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Lorenz attractor\n\nThis is an example of plotting Edward Lorenz's 1963 `\"Deterministic Nonperiodic\nFlow\"`_ in a 3-dimensional space using mplot3d.\n\n https://journals.ametsoc.org/view/journals/atsc/20/2/1520-0469_1963_020_0130_dnf_2_0_co_2.xml\n\n

Note

Because this is a simple non-linear ODE, it would be more easily done using\n SciPy's ODE solver, but this approach depends only upon NumPy.

\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef lorenz(xyz, *, s=10, r=28, b=2.667):\n \"\"\"\n Parameters\n ----------\n xyz : array-like, shape (3,)\n Point of interest in three-dimensional space.\n s, r, b : float\n Parameters defining the Lorenz attractor.\n\n Returns\n -------\n xyz_dot : array, shape (3,)\n Values of the Lorenz attractor's partial derivatives at *xyz*.\n \"\"\"\n x, y, z = xyz\n x_dot = s*(y - x)\n y_dot = r*x - y - x*z\n z_dot = x*y - b*z\n return np.array([x_dot, y_dot, z_dot])\n\n\ndt = 0.01\nnum_steps = 10000\n\nxyzs = np.empty((num_steps + 1, 3)) # Need one more for the initial values\nxyzs[0] = (0., 1., 1.05) # Set initial values\n# Step through \"time\", calculating the partial derivatives at the current point\n# and using them to estimate the next point\nfor i in range(num_steps):\n xyzs[i + 1] = xyzs[i] + lorenz(xyzs[i]) * dt\n\n# Plot\nax = plt.figure().add_subplot(projection='3d')\n\nax.plot(*xyzs.T, lw=0.5)\nax.set_xlabel(\"X Axis\")\nax.set_ylabel(\"Y Axis\")\nax.set_zlabel(\"Z Axis\")\nax.set_title(\"Lorenz Attractor\")\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. tags::\n plot-type: 3D,\n level: intermediate\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }