Classical Gibbs thermodynamics treats phase boundaries as infinitely sharp mathematical surfaces of zero thickness, yet inside the chemical spinodal (), a quenched solid solution decomposes spontaneously without any nucleation barrier, forming nanoscale composition waves whose diffuse interfaces are several atomic planes wide. If we wrote Fick’s law with a negative diffusivity , the shortest grid-scale wavelengths () would grow at an unbounded rate (), rendering the PDE mathematically ill-posed. In 1958, John W. Cahn and John E. Hilliard removed this divergence by adding the gradient energy penalty to the free-energy functional. In this lecture we derive and verify the exact planar diffuse interface, interfacial tension , the Cahn–Hilliard dispersion relation , and the severe biharmonic stiffness of explicit finite differences versus semi-implicit spectral integration.
Learning objectives¶
Evaluate the symmetric Landau double-well free-energy density , chemical potential , and spinodal curvature via
phase_field.double_well_potential.Verify the exact 1-D equilibrium planar interface with diffuse width , energy equipartition, and surface tension via
phase_field.equilibrium_interface_profile_1d.Analyze linear spinodal amplification , critical wavenumber , and fastest-growing wavelength using
phase_field.cahn_hilliard_dispersion.Contrast the fourth-order explicit stability bottleneck of
phase_field.cahn_hilliard_1d_fdagainst semi-implicit Fourier integration inphase_field.cahn_hilliard_1d_spectral.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engmaterials
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engmaterials" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engmaterials.git"], check=True)
import engmaterials
import inspect
import numpy as np
import matplotlib.pyplot as plt
from engmaterials import (atomistics, constants, diffraction, elasticity, kinetics_selection,
lattices, phase_field, phase_thermodynamics)
from engmaterials.plotting import label_panels, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Principles and governing equations¶
Consider an inhomogeneous binary alloy with local conserved solute mole fraction . In Cahn–Hilliard continuum thermodynamics (Cahn & Hilliard, J. Chem. Phys. 28, 258, 1958), the total Ginzburg–Landau free energy sums a homogeneous bulk Landau free-energy density and a non-local gradient penalty resisting sharp composition jumps:
where sets the double-well barrier height between equilibrium phases and , and is the gradient energy coefficient. Differentiating (phase_field.double_well_potential) gives:
Setting locates the chemical spinodal inflection points , inside which triggers barrierless uphill diffusion.
1.1 Variational Chemical Potential & Exact Planar Diffuse Interface¶
Taking the variational derivative , a 1-D planar equilibrium interface connecting to satisfies . Multiplying by and integrating from yields exact pointwise energy equipartition , with closed-form solution (phase_field.equilibrium_interface_profile_1d):
heading("Demonstration 1: Landau Double-Well Spinodal Region & Exact Planar tanh Interface")
c_grid = np.linspace(0.0, 1.0, 401)
W_val, kappa_val = 2.0, 0.5
dw = phase_field.double_well_potential(c_grid, W=W_val)
cs_minus = 0.5 * (1.0 - 1.0 / np.sqrt(3.0))
cs_plus = 0.5 * (1.0 + 1.0 / np.sqrt(3.0))
assert np.isclose(phase_field.double_well_potential(cs_minus, W=W_val)["d2f_dc2"], 0.0, atol=1e-14)
assert np.isclose(phase_field.double_well_potential(0.5, W=W_val)["d2f_dc2"], -1.0 * W_val, atol=1e-14)
x_dom = np.linspace(-10.0, 10.0, 2001)
prof = phase_field.equilibrium_interface_profile_1d(x_dom, W=W_val, kappa=kappa_val, x0=0.0)
f_prof = phase_field.double_well_potential(prof["c"], W=W_val)["f"]
grad_e = 0.5 * kappa_val * (prof["dc_dx"] ** 2)
integrand = f_prof + grad_e
sigma_num = float(np.sum(0.5 * (integrand[:-1] + integrand[1:]) * np.diff(x_dom)))
print(f"Spinodal interval where f''(c) < 0 : [{cs_minus:.6f}, {cs_plus:.6f}]")
print(f"Diffuse interface width l_w : {prof['interface_width']:.6f} (exact sqrt(2*kappa/W) = {np.sqrt(2*kappa_val/W_val):.6f})")
print(f"Pointwise equipartition max |f - 0.5*kappa*(dc/dx)^2| : {np.max(np.abs(f_prof - grad_e)):.2e}")
print(f"Surface tension sigma: quadrature = {sigma_num:.8f} vs exact sqrt(kappa*W/18) = {prof['interfacial_energy_exact']:.8f}")
assert np.allclose(f_prof, grad_e, atol=1e-14)
assert np.isclose(sigma_num, prof["interfacial_energy_exact"], rtol=1e-6)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
ax1.plot(c_grid, dw["f"], lw=2.2, label=r"$f(c) = W c^2(1-c)^2$")
ax1.plot(c_grid, 0.1 * dw["d2f_dc2"], "--", lw=1.8, label=r"$0.1\,f''(c)$")
ax1.axhline(0.0, color="k", lw=0.8)
ax1.axvspan(cs_minus, cs_plus, alpha=0.18, color="tab:red", label=r"Spinodal ($f''(c) \leq 0$)")
ax1.set_xlabel("Composition $c$ [-]")
ax1.set_ylabel("Free-energy density [arb. units]")
ax1.set_title("Landau Double-Well & Chemical Spinodal")
ax1.legend(fontsize=8)
ax2.plot(x_dom, prof["c"], lw=2.2, label=r"$c_{\mathrm{eq}}(x)$")
ax2.plot(x_dom, f_prof / np.max(f_prof), "--", lw=1.8, label=r"Normalized $f(c) = \frac{\kappa}{2}(dc/dx)^2$")
ax2.set_xlim(-4.0, 4.0)
ax2.set_xlabel("Position $x$ [arb. length]")
ax2.set_ylabel("Composition / Normalized Energy [-]")
ax2.set_title(rf"Diffuse Planar Interface ($\ell_w = {prof['interface_width']:.2f}$, $\sigma = {prof['interfacial_energy_exact']:.4f}$)")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
Demonstration 1: Landau Double-Well Spinodal Region & Exact Planar tanh Interface
=================================================================================
Spinodal interval where f''(c) < 0 : [0.211325, 0.788675]
Diffuse interface width l_w : 0.707107 (exact sqrt(2*kappa/W) = 0.707107)
Pointwise equipartition max |f - 0.5*kappa*(dc/dx)^2| : 1.39e-16
Surface tension sigma: quadrature = 0.23570226 vs exact sqrt(kappa*W/18) = 0.23570226

Figure 12.1. (a) Double-well free-energy density and its second derivative (scaled by 0.1); the shaded band is the spinodal. (b) Equilibrium interface profile and the normalized energy density across it.
What Demonstration 1 shows. and act in opposite directions on the width: increasing the gradient penalty widens the interface (), whereas increasing the chemical barrier sharpens it (), while both raise the excess interfacial energy . Pointwise equipartition holds to 10-15, and numerical quadrature matches to 8 significant digits (here , ).
2. Linear Spinodal Dispersion & Wavelength Selection¶
Because solute atoms are conserved, the flux obeys the continuity equation , giving the fourth-order nonlinear Cahn–Hilliard PDE:
Substituting an infinitesimal Fourier composition wave around a uniform alloy and retaining linear terms in yields the Cahn–Hilliard dispersion relation (phase_field.cahn_hilliard_dispersion):
When , long-wavelength perturbations with grow exponentially (), while short-wavelength modes are damped () by the capillary penalty:
heading("Demonstration 2: Cahn-Hilliard Linear Dispersion Curve omega(k) Inside vs Outside Spinodal")
k_vals = np.linspace(0.0, 2.2, 300)
M_ch = 1.0
fig, ax = plt.subplots(figsize=(7.5, 4.2))
print(f"{'Alloy c0':>8s} | {'d2f/dc2':>10s} | {'Unstable?':>10s} | {'k_c':>9s} | {'k_max':>9s} | {'lambda_max':>11s} | {'omega_max':>10s}")
print("-" * 82)
for c0_val, style in [(0.50, "-"), (0.35, "--"), (0.25, "-."), (0.12, ":")]:
disp = phase_field.cahn_hilliard_dispersion(k_vals, c0=c0_val, W=W_val, kappa=kappa_val, M=M_ch)
print(f"{c0_val:8.2f} | {disp['d2f_dc2']:10.4f} | {str(disp['spinodal_unstable']):>10s} | "
f"{disp['k_c']:9.4f} | {disp['k_max']:9.4f} | {disp['lambda_max']:11.4f} | {disp['omega_max']:10.4f}")
ax.plot(k_vals, disp["omega"], ls=style, lw=2.1, label=rf"$c_0 = {c0_val:.2f}$ ($f'' = {disp['d2f_dc2']:.2f}$)")
disp_50 = phase_field.cahn_hilliard_dispersion(k_vals, c0=0.50, W=W_val, kappa=kappa_val, M=M_ch)
disp_12 = phase_field.cahn_hilliard_dispersion(k_vals, c0=0.12, W=W_val, kappa=kappa_val, M=M_ch)
assert disp_50["spinodal_unstable"] is True and np.isclose(disp_50["lambda_max"], 2.0 * np.pi * np.sqrt(2.0) / disp_50["k_c"])
assert disp_12["spinodal_unstable"] is False and np.all(disp_12["omega"] <= 0.0)
ax.axhline(0.0, color="k", lw=0.9)
ax.scatter([disp_50["k_max"]], [disp_50["omega_max"]], color="tab:red", zorder=5, label=rf"Peak $k_{{\max}} = {disp_50['k_max']:.3f}$")
ax.set_xlabel("Wavenumber $k$ [1/length]")
ax.set_ylabel("Amplification rate $\\omega(k)$ [1/time]")
ax.set_title("Cahn–Hilliard Spinodal Dispersion Relation $\\omega(k) = -M k^2[f''(c_0) + \\kappa k^2]$")
ax.legend(fontsize=8)
plt.show()
Demonstration 2: Cahn-Hilliard Linear Dispersion Curve omega(k) Inside vs Outside Spinodal
==========================================================================================
Alloy c0 | d2f/dc2 | Unstable? | k_c | k_max | lambda_max | omega_max
----------------------------------------------------------------------------------
0.50 | -2.0000 | True | 2.0000 | 1.4142 | 4.4429 | 2.0000
0.35 | -1.4600 | True | 1.7088 | 1.2083 | 5.2000 | 1.0658
0.25 | -0.5000 | True | 1.0000 | 0.7071 | 8.8858 | 0.1250
0.12 | 1.4656 | False | 0.0000 | 0.0000 | inf | 0.0000

Figure 12.2. Growth rate of a small composition wave for four mean compositions; the point marks the fastest-growing wavenumber at .
What Demonstration 2 shows. Without gradient energy (), diverges parabolically as . The fourth-order term bends back below zero beyond , which selects the wavelength at . As moves from the spinodal center (0.50) toward the spinodal boundary (0.2113), weakens, shifting to longer wavelengths (8.886 at ) and lowering by a factor of 16. Outside the spinodal (, metastable binodal region), for all : small composition fluctuations decay, so phase separation requires finite-amplitude nucleation.
3. Biharmonic Stiffness: Explicit FD vs. Semi-Implicit Spectral¶
Discretizing Eq. (2.1) on an -point periodic grid of spacing via conservative second-order finite differences (phase_field.cahn_hilliard_1d_fd) approximates the fourth derivative , whose highest Nyquist mode () has discrete eigenvalue . Forward Euler time stepping therefore suffers a punitive fourth-order stability restriction:
Halving shrinks the maximum stable time step by . By contrast, phase_field.cahn_hilliard_1d_spectral treats the stiff linear term implicitly in Fourier space while keeping the nonlinear chemical term explicit:
We verify both solvers at a stable fine step against analytical linear growth , and then test ( above ).
heading("Demonstration 3: 1-D Explicit FD vs Semi-Implicit Spectral Solver & Early-Time Mode Growth")
N_1d = 64
L_1d = 32.0 # dx = 0.5 -> dx^4 / (8*M*kappa) = 0.0625 / 4.0 = 0.015625
dx_1d = L_1d / N_1d
x_1d = np.arange(N_1d) * dx_1d
m_mode = 5 # k_m = 2*pi*5 / 32 = 0.98175 (inside the unstable band, below k_max = 1.414)
k_mode = 2.0 * np.pi * m_mode / L_1d
amp0 = 1e-3
c_init_1d = 0.5 + amp0 * np.cos(k_mode * x_1d)
# 1) Small stable step dt = 0.005 up to t = 2.0:
fd_small = phase_field.cahn_hilliard_1d_fd(c_init_1d, L=L_1d, dt=0.005, n_steps=400, M=M_ch, W=W_val, kappa=kappa_val, record_every=100)
sp_small = phase_field.cahn_hilliard_1d_spectral(c_init_1d, L=L_1d, dt=0.005, n_steps=400, M=M_ch, W=W_val, kappa=kappa_val, record_every=100)
omega_exact = phase_field.cahn_hilliard_dispersion(k_mode, c0=0.5, W=W_val, kappa=kappa_val, M=M_ch)["omega"]
amp_sp_t2 = float(2.0 * np.abs(np.fft.fft(sp_small["final"] - 0.5)[m_mode]) / N_1d)
amp_lin_t2 = float(amp0 * np.exp(omega_exact * 2.0))
print(f"Grid dx = {dx_1d:.3f} -> Explicit biharmonic limit dx^4/(8*M*kappa) = {(dx_1d**4)/(8*M_ch*kappa_val):.5f}")
print(f"At t = 2.0 (dt=0.005): Spectral amp = {amp_sp_t2:.6f} vs Linear Theory A0*exp(omega*t) = {amp_lin_t2:.6f}")
print(f"Max |c_FD - c_Spectral| at dt = 0.005 : {np.max(np.abs(fd_small['final'] - sp_small['final'])):.4e}")
assert np.isclose(amp_sp_t2, amp_lin_t2, rtol=2.5e-2)
assert np.max(np.abs(fd_small["final"] - sp_small["final"])) < 1e-3
# 2) Large time step dt = 0.10 (t_end = 25.0, full nonlinear phase separation into plateaus 0 and 1):
with np.errstate(over="ignore", invalid="ignore"):
fd_large = phase_field.cahn_hilliard_1d_fd(c_init_1d, L=L_1d, dt=0.10, n_steps=250, M=M_ch, W=W_val, kappa=kappa_val, record_every=50)
sp_large = phase_field.cahn_hilliard_1d_spectral(c_init_1d, L=L_1d, dt=0.10, n_steps=250, M=M_ch, W=W_val, kappa=kappa_val, record_every=50)
fd_blew_up = bool((not np.all(np.isfinite(fd_large["final"]))) or np.max(np.abs(fd_large["final"])) > 1e6)
print(f"At dt = 0.10 (> dt_crit): Explicit FD blew up = {fd_blew_up} | Spectral bounded in [{sp_large['final'].min():.4f}, {sp_large['final'].max():.4f}]")
print(f"Spectral free energy F(0) = {sp_large['free_energies'][0]:.4f} -> F(25) = {sp_large['free_energies'][-1]:.4f} (monotone decay)")
assert fd_blew_up is True
assert np.all(np.diff(sp_large["free_energies"]) <= 1e-12)
assert abs(sp_large["mean_compositions"][-1] - 0.5) < 1e-14
Demonstration 3: 1-D Explicit FD vs Semi-Implicit Spectral Solver & Early-Time Mode Growth
==========================================================================================
Grid dx = 0.500 -> Explicit biharmonic limit dx^4/(8*M*kappa) = 0.01562
At t = 2.0 (dt=0.005): Spectral amp = 0.018326 vs Linear Theory A0*exp(omega*t) = 0.018659
Max |c_FD - c_Spectral| at dt = 0.005 : 5.9729e-04
At dt = 0.10 (> dt_crit): Explicit FD blew up = True | Spectral bounded in [0.0224, 0.9776]
Spectral free energy F(0) = 4.0000 -> F(25) = 2.3536 (monotone decay)
What Demonstration 3 shows. At , explicit finite differences and Fourier spectral integration agree closely (largest difference ), and the amplitude at is within of the linear growth law . Increasing the step to makes cahn_hilliard_1d_fd diverge, whereas cahn_hilliard_1d_spectral carries the perturbation into plateaus near and separated by interfaces, conserves the mean composition to and lowers from 4.000 to 2.354. Five domains have ten interfaces, and .
4. Sensitivity to the parameters¶
What happens to the emergent spinodal microstructure if we vary the gradient energy coefficient at fixed ? We verify the simultaneous scaling of interface width , interfacial tension , fastest spinodal wavelength , and peak amplification rate .
heading("Demonstration 4: Gradient-Energy Sensitivity Sweep kappa -> l_w, sigma, lambda_max, omega_max")
kappas = np.array([0.125, 0.25, 0.50, 1.00, 2.00])
print(f"{'kappa':>8s} | {'Width l_w':>11s} | {'Tension sigma':>14s} | {'lambda_max':>12s} | {'lambda_max / l_w':>17s} | {'omega_max':>11s}")
print("-" * 88)
ratios_lam_lw = []
for kap in kappas:
pr = phase_field.equilibrium_interface_profile_1d(np.array([0.0]), W=W_val, kappa=float(kap))
dp = phase_field.cahn_hilliard_dispersion(1.0, c0=0.50, W=W_val, kappa=float(kap), M=M_ch)
ratio = dp["lambda_max"] / pr["interface_width"]
ratios_lam_lw.append(ratio)
print(f"{kap:8.3f} | {pr['interface_width']:11.4f} | {pr['interfacial_energy_exact']:14.5f} | "
f"{dp['lambda_max']:12.4f} | {ratio:17.6f} | {dp['omega_max']:11.4f}")
# Universal dimensionless ratio at c0 = 0.5: lambda_max / l_w = 2*pi == 6.283185 independent of kappa and W
assert np.allclose(ratios_lam_lw, 2.0 * np.pi, rtol=1e-12)
Demonstration 4: Gradient-Energy Sensitivity Sweep kappa -> l_w, sigma, lambda_max, omega_max
=============================================================================================
kappa | Width l_w | Tension sigma | lambda_max | lambda_max / l_w | omega_max
----------------------------------------------------------------------------------------
0.125 | 0.3536 | 0.11785 | 2.2214 | 6.283185 | 8.0000
0.250 | 0.5000 | 0.16667 | 3.1416 | 6.283185 | 4.0000
0.500 | 0.7071 | 0.23570 | 4.4429 | 6.283185 | 2.0000
1.000 | 1.0000 | 0.33333 | 6.2832 | 6.283185 | 1.0000
2.000 | 1.4142 | 0.47140 | 8.8858 | 6.283185 | 0.5000
Inside the algorithm¶
What Demonstration 4 shows. At the critical composition (), , which yields a universal dimensionless ratio independent of both and . Every nascent spinodal wave is diffuse interface widths across.
Below we inspect phase_field.equilibrium_interface_profile_1d and phase_field.cahn_hilliard_dispersion, and verify a NumPy implementation side by side to rounding error.
Check against the library¶
heading("Inside the Algorithm: phase_field.equilibrium_interface_profile_1d & cahn_hilliard_dispersion")
print(show_source(phase_field.equilibrium_interface_profile_1d))
print(show_source(phase_field.cahn_hilliard_dispersion))
x_chk = np.linspace(-5.0, 5.0, 101)
lw_hand = np.sqrt(2.0 * kappa_val / W_val)
c_hand = 0.5 * (1.0 + np.tanh(x_chk / lw_hand))
prof_lib = phase_field.equilibrium_interface_profile_1d(x_chk, W=W_val, kappa=kappa_val)
assert np.allclose(c_hand, prof_lib["c"], rtol=1e-15, atol=1e-15)
k_chk = np.linspace(0.1, 2.0, 20)
f2_hand = 2.0 * W_val * (1.0 - 6.0 * 0.4 + 6.0 * (0.4 ** 2))
omega_hand = -M_ch * (k_chk ** 2) * (f2_hand + kappa_val * (k_chk ** 2))
omega_lib = phase_field.cahn_hilliard_dispersion(k_chk, c0=0.4, W=W_val, kappa=kappa_val, M=M_ch)["omega"]
print("Max |omega_hand - omega_lib|:", float(np.max(np.abs(omega_hand - omega_lib))))
assert np.allclose(omega_hand, omega_lib, rtol=1e-15, atol=1e-15)
Inside the Algorithm: phase_field.equilibrium_interface_profile_1d & cahn_hilliard_dispersion
=============================================================================================
def equilibrium_interface_profile_1d(
x: np.ndarray,
W: float = 1.0,
kappa: float = 1.0,
x0: float = 0.0,
) -> dict:
"""Compute exact 1-D diffuse interface c(x) = 0.5*[1 + tanh((x-x0)/w)] and surface tension sqrt(kappa*W/18)."""
if W <= 0.0 or kappa <= 0.0:
raise ValueError("W and kappa must be strictly positive.")
xg = np.asarray(x, dtype=float)
width = float(np.sqrt(2.0 * kappa / W))
c_prof = 0.5 * (1.0 + np.tanh((xg - x0) / width))
dc_dx = (0.5 / width) / (np.cosh((xg - x0) / width) ** 2)
sigma_exact = float(np.sqrt(kappa * W / 18.0))
return {
"c": c_prof,
"dc_dx": dc_dx,
"interface_width": width,
"interfacial_energy_exact": sigma_exact,
}
def cahn_hilliard_dispersion(
k: float | np.ndarray,
c0: float = 0.5,
W: float = 1.0,
kappa: float = 1.0,
M: float = 1.0,
) -> dict:
"""Evaluate Cahn-Hilliard dispersion omega(k) = -M*k^2*[f''(c0) + kappa*k^2] and fastest spinodal mode k_max."""
k_arr = np.asarray(k, dtype=float)
f2 = double_well_potential(float(c0), W=W)["d2f_dc2"]
omega = -M * (k_arr**2) * (f2 + kappa * (k_arr**2))
if f2 < 0.0:
kc = float(np.sqrt(-f2 / kappa))
k_max = float(kc / np.sqrt(2.0))
lam_max = float(2.0 * np.pi / k_max)
omega_max = float(M * (f2**2) / (4.0 * kappa))
unstable = True
else:
kc = 0.0
k_max = 0.0
lam_max = float(np.inf)
omega_max = 0.0
unstable = False
return {
"omega": float(omega) if np.ndim(k) == 0 else omega,
"d2f_dc2": float(f2),
"spinodal_unstable": unstable,
"k_c": kc,
"k_max": k_max,
"lambda_max": lam_max,
"omega_max": omega_max,
}
Max |omega_hand - omega_lib|: 0.0
Exercises¶
Worked solutions are in 12_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. On a periodic domain (), construct a smooth two-interface slab for , evaluate
phase_field.ginzburg_landau_free_energy_1d, and verify across three pairs that to within 10-5.Find how it fails. Verify that
equilibrium_interface_profile_1draisesValueErrorwhenW <= 0orkappa <= 0, and check numerically oncahn_hilliard_1d_fd() that is stable at () yet blows up at () due to the biharmonic CFL penalty.Implement it yourself. Implement
my_cahn_hilliard_1d_spectral(c_init, L, dt, n_steps, M=1.0, W=1.0, kappa=1.0)in pure NumPy usingnp.fft.fftandnp.fft.ifft, verify its final composition profile matchesphase_field.cahn_hilliard_1d_spectralto< 1e-13, and verify .
heading("Self-check for the exercises")
x_per = np.linspace(0.0, 40.0, 256, endpoint=False)
prof_ref = phase_field.equilibrium_interface_profile_1d(x_per, W=4.0, kappa=0.5)
lw_ref = prof_ref["interface_width"]
c_two_int = 0.5 * (np.tanh((x_per - 10.0) / lw_ref) - np.tanh((x_per - 30.0) / lw_ref))
F_two = phase_field.ginzburg_landau_free_energy_1d(c_two_int, L=40.0, W=4.0, kappa=0.5)
two_sigma = 2.0 * prof_ref["interfacial_energy_exact"]
print(f"Periodic two-interface F[c] = {F_two:.8f} vs exact 2*sigma = {two_sigma:.8f}")
assert np.isclose(F_two, two_sigma, rtol=1e-6)
print("All checks passed.")
Self-check for the exercises
============================
Periodic two-interface F[c] = 0.66666667 vs exact 2*sigma = 0.66666667
All checks passed.