Quantum Harmonic Oscillator¶
We solve the stationary Schrödinger equation for the quantum harmonic oscillator using spectral methods provided by numgrids. This notebook demonstrates how Chebyshev grids deliver exponential convergence compared to equidistant finite-difference grids.
Physics background¶
The time-independent Schrödinger equation is the eigenvalue problem
where the Hamiltonian for the one-dimensional harmonic oscillator (in natural units \(\hbar = m = \omega = 1\)) reads
The analytical eigenvalues are
and the eigenstates are Hermite functions (Gaussians multiplied by Hermite polynomials).
We discretize \(H\) on a finite domain \([-8, 8]\) with \(\psi = 0\) at the boundaries and solve the resulting matrix eigenvalue problem numerically.
[1]:
import numpy as np
import matplotlib.pyplot as plt
from numgrids import *
plt.rcParams.update({"figure.dpi": 120, "font.size": 11})
Grid and Hamiltonian¶
We use a Chebyshev grid with 60 points on \([-8, 8]\). Chebyshev differentiation matrices achieve spectral (exponential) accuracy for smooth functions.
The Hamiltonian is written down exactly as in the formula: the kinetic term \(-\frac{1}{2} d^2/dx^2\) is an Operator, and adding the array \(\frac{1}{2}x^2\) adds the multiplication operator for the potential.
[2]:
L = 8.0
grid = Grid(x=chebyshev(60, -L, L))
x = grid.coords
H = -0.5 * grid.diff_operator(2) + 0.5 * x**2
print(H)
Operator(grid=Grid(60,), nnz=3600)
Eigenvalue solve¶
H.eig computes the lowest eigenpairs. The boundary condition \(\psi(\pm L) = 0\) is passed as bcs=0. Dirichlet points are eliminated from the problem internally, so – unlike naively replacing matrix rows – no spurious eigenvalues appear and no filtering is needed.
[3]:
n_states = 8
energies, states = H.eig(k=n_states, bcs=0)
print("Computed eigenvalues vs analytical (E_n = n + 1/2):")
print(f"{'n':>3s} {'Numerical':>14s} {'Analytical':>10s} {'Error':>12s}")
print("-" * 45)
for n, E in enumerate(energies):
print(f"{n:3d} {E:14.10f} {n + 0.5:10.1f} {abs(E - n - 0.5):12.2e}")
Computed eigenvalues vs analytical (E_n = n + 1/2):
n Numerical Analytical Error
---------------------------------------------
0 0.5000000000 0.5 6.55e-15
1 1.5000000000 1.5 1.78e-15
2 2.5000000000 2.5 8.44e-15
3 3.5000000000 3.5 3.55e-15
4 4.5000000000 4.5 6.75e-14
5 5.5000000000 5.5 1.01e-12
6 6.5000000000 6.5 1.05e-11
7 7.4999999999 7.5 9.76e-11
Normalize eigenstates¶
eig returns eigenvectors with unit Euclidean norm. For wave functions we want \(\int |\psi_n|^2 dx = 1\), which we get with the grid’s spectrally accurate quadrature (Clenshaw–Curtis). We also fix the sign so that each state starts positive on the left.
[4]:
psis = []
for psi in states:
psi = psi / np.sqrt(grid.integrate(psi**2))
left = psi[np.argmax(np.abs(psi) > 1e-3 * np.abs(psi).max())] # first non-negligible value
psis.append(np.sign(left) * psi)
print("Normalization check:", [round(grid.integrate(p**2), 12) for p in psis])
Normalization check: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
Energy level diagram with eigenstates¶
Each eigenstate \(\psi_n(x)\) is plotted offset vertically by its energy \(E_n\). For smooth curves we evaluate the states on a fine uniform mesh with spectral interpolation, which preserves the accuracy of the Chebyshev representation.
[5]:
x_fine = np.linspace(-L, L, 500)
psi_fine = [grid.interpolate(psi, x_fine, method="spectral") for psi in psis]
fig, ax = plt.subplots(figsize=(8, 8))
ax.fill_between(x_fine, 0.5 * x_fine**2, alpha=0.1, color="gray", label="$V(x) = x^2/2$")
ax.plot(x_fine, 0.5 * x_fine**2, color="gray", linewidth=1.0, alpha=0.6)
colors = plt.cm.tab10(np.arange(n_states))
scale = 1.5
for n, (E, psi) in enumerate(zip(energies, psi_fine)):
ax.axhline(n + 0.5, color="gray", linestyle="--", linewidth=0.5, alpha=0.7)
ax.plot(x_fine, scale * psi + E, color=colors[n], linewidth=1.2, label=f"$n={n}$, $E={E:.4f}$")
ax.fill_between(x_fine, E, scale * psi + E, alpha=0.15, color=colors[n])
ax.set_xlim(-6, 6)
ax.set_ylim(-0.5, n_states + 1.5)
ax.set_xlabel("$x$")
ax.set_ylabel(r"Energy / $\psi_n(x) + E_n$")
ax.set_title("Quantum Harmonic Oscillator -- Energy Levels and Eigenstates")
ax.legend(loc="upper right", fontsize=8, ncol=2)
plt.tight_layout()
plt.show()
Probability densities¶
Plot \(|\psi_n(x)|^2\) for the first four eigenstates, together with the classical turning points \(x = \pm\sqrt{2E_n}\).
[6]:
fig, axes = plt.subplots(2, 2, figsize=(10, 7), sharex=True)
for n, ax in enumerate(axes.flat):
prob = psi_fine[n]**2
ax.plot(x_fine, prob, color=colors[n], linewidth=1.5)
ax.fill_between(x_fine, prob, alpha=0.2, color=colors[n])
x_tp = np.sqrt(2 * energies[n])
ax.axvline(x_tp, color="gray", linestyle=":", linewidth=0.8)
ax.axvline(-x_tp, color="gray", linestyle=":", linewidth=0.8)
ax.set_xlim(-6, 6)
ax.set_title(f"$n = {n}$, $E_{n} = {energies[n]:.4f}$")
ax.set_ylabel(r"$|\psi_n(x)|^2$")
for ax in axes[1]:
ax.set_xlabel("$x$")
fig.suptitle("Probability Densities", fontsize=14, y=1.01)
plt.tight_layout()
plt.show()
Convergence study: Equidistant vs Chebyshev¶
We compare the convergence of the ground-state energy \(E_0\) with the number of grid points \(N\) for equidistant (finite difference) and Chebyshev (spectral) grids. convergence_study runs the computation for each resolution and compares with the exact value \(E_0 = 1/2\).
The key prediction from numerical analysis:
Equidistant grids with finite differences converge algebraically (polynomial in \(N\)).
Chebyshev grids with spectral differentiation converge exponentially (straight line on a semilog plot).
[7]:
def ground_state_energy(grid):
x = grid.coords
H = -0.5 * grid.diff_operator(2) + 0.5 * x**2
energies, _ = H.eig(k=1, bcs=0)
return energies[0]
N_values = [20, 30, 40, 60, 80, 100]
equi = convergence_study(lambda n: Grid(equidistant(n, -L, L)), ground_state_energy, N_values, exact=0.5)
cheb = convergence_study(lambda n: Grid(chebyshev(n, -L, L)), ground_state_energy, N_values, exact=0.5)
print(f"{'N':>5s} {'Equidistant error':>18s} {'Chebyshev error':>16s}")
for n, e1, e2 in zip(N_values, equi.errors, cheb.errors):
print(f"{n:5d} {e1:18.2e} {e2:16.2e}")
print(f"\nFitted algebraic order of the equidistant grid: {equi.order:.1f}")
N Equidistant error Chebyshev error
20 4.46e-03 9.63e-03
30 8.90e-04 1.48e-05
40 2.81e-04 1.89e-09
60 5.51e-05 6.55e-15
80 1.73e-05 1.92e-14
100 7.05e-06 3.44e-15
Fitted algebraic order of the equidistant grid: 4.0
[8]:
fig, ax = plt.subplots(figsize=(8, 5))
ax.semilogy(equi.ns, equi.errors, "o-", linewidth=1.5, markersize=7, label="Equidistant (finite differences)")
ax.semilogy(cheb.ns, np.maximum(cheb.errors, 1e-16), "s-", linewidth=1.5, markersize=7,
label="Chebyshev (spectral)")
ax.set_xlabel("Number of grid points $N$")
ax.set_ylabel("$|E_0 - 0.5|$")
ax.set_title("Convergence of Ground-State Energy: Equidistant vs Chebyshev")
ax.legend(fontsize=11)
ax.grid(True, which="both", alpha=0.3)
plt.tight_layout()
plt.show()
Summary¶
The Hamiltonian is written as a formula,
-0.5 * grid.diff_operator(2) + 0.5 * x**2, andH.eig(k, bcs=0)returns the eigenpairs without spurious modes from the boundary conditions.grid.integratenormalizes wave functions andgrid.interpolate(..., method="spectral")evaluates them anywhere with spectral accuracy.The Chebyshev spectral method achieves exponential convergence, reaching machine precision with relatively few grid points, whereas equidistant finite differences converge only algebraically. Switching between the two only requires changing the axis.