InΒ [1]:
# Setup: installs the qplay package if it is missing (for example on Google Colab).
import importlib.util, subprocess, sys
if importlib.util.find_spec("qplay") is None:
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"quantum-playground"], check=True)
InΒ [2]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from qplay import numerics, waves, chaos
Newton's methodΒΆ
Solve $x^2 - 2 = 0$ by iterating $x_{n+1} = x_n - f(x_n)/f'(x_n)$, which converges quadratically.
InΒ [3]:
x = 1.0
for i in range(6):
x = x - (x * x - 2) / (2 * x)
print(i, x, abs(x - np.sqrt(2)))
0 1.5 0.08578643762690485 1 1.4166666666666667 0.002453104293571595 2 1.4142156862745099 2.1239014147411694e-06 3 1.4142135623746899 1.5947243525715749e-12 4 1.4142135623730951 0.0 5 1.414213562373095 2.220446049250313e-16
Fourier series of a square waveΒΆ
$$\operatorname{sgn}(\sin x) = \frac{4}{\pi}\sum_{k\ \mathrm{odd}}\frac{\sin kx}{k}.$$
Note the overshoot near the jumps, the Gibbs phenomenon, which never goes away however many terms you add.
InΒ [4]:
period = 2 * np.pi
a0, a, b = waves.fourier_coefficients(lambda s: np.sign(np.sin(s)), period, 50, points=[np.pi])
x = np.linspace(0, 2 * np.pi, 1000)
for n in (1, 5, 49):
plt.plot(x, waves.fourier_sum(a0, a[:n], b[:n], x, period), label=f"{n} terms")
plt.legend();
The road to chaosΒΆ
For the logistic map $x_{n+1}=r\,x_n(1-x_n)$ the Lyapunov exponent $\lambda$ is negative for stable orbits and positive for chaos.
InΒ [5]:
r, xs = chaos.bifurcation(np.linspace(2.8, 4.0, 1000))
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 6), sharex=True)
ax1.scatter(r, xs, s=0.1, c="k", alpha=0.3, linewidths=0)
rs = np.linspace(2.8, 4.0, 300)
ax2.plot(rs, [chaos.lyapunov_logistic(v, n=2000) for v in rs], lw=0.8)
ax2.axhline(0, color="r", lw=0.5); ax2.set_xlabel("r"); ax2.set_ylabel(r"$\lambda$");
FractalsΒΆ
The Mandelbrot set is the set of $c$ for which $z \to z^2 + c$ stays bounded when started from $z=0$.
InΒ [6]:
plt.figure(figsize=(8, 5))
plt.imshow(chaos.mandelbrot(width=800, height=520, max_iter=150), extent=[-2.2, 0.8, -1.2, 1.2], cmap="magma", origin="lower")
plt.grid(False);
InΒ [7]:
plt.figure(figsize=(7, 5))
plt.imshow(chaos.julia(-0.8 + 0.156j, max_iter=150), extent=[-1.6, 1.6, -1.2, 1.2], cmap="twilight_shifted", origin="lower")
plt.grid(False);
Your turnΒΆ
- Estimate $\pi$ with
numerics.monte_carlo_piand plot the error against $N$. How fast does it shrink? - Zoom into the Mandelbrot set by changing
xlimandylim.