Chapter 2: The Heat EquationΒΆ

Modeling Heat FlowΒΆ

How does temperature change over time when heat flows through a material?

The SetupΒΆ

  • Temperature distribution: T(x, t)

  • x = position along a rod

  • t = time

Question: How does T change?

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.animation import FuncAnimation
from IPython.display import HTML

sns.set_style('whitegrid')
plt.rcParams['figure.figsize'] = (14, 10)
np.set_printoptions(precision=3, suppress=True)

Deriving the Heat EquationΒΆ

Key Physical InsightΒΆ

Heat flows from hot to cold. The rate depends on the temperature gradient.

Fourier’s Law: $\( q = -k\frac{\partial T}{\partial x} \)$

where q = heat flux, k = thermal conductivity

The ResultΒΆ

\[ \boxed{\frac{\partial T}{\partial t} = \alpha \frac{\partial^2 T}{\partial x^2}} \]

Interpretation: Where there’s curvature in space, there’s change in time!

def visualize_heat_intuition():
    """Show why curvature causes change in time."""
    x = np.linspace(0, 10, 100)
    
    # Three temperature profiles
    fig, axes = plt.subplots(3, 1, figsize=(12, 10))
    
    scenarios = [
        ("Concave (dΒ²T/dxΒ² > 0)", lambda x: -0.1*(x-5)**2 + 3, "Temperature increases"),
        ("Linear (dΒ²T/dxΒ² = 0)", lambda x: 0.2*x + 1, "Temperature constant"),
        ("Convex (dΒ²T/dxΒ² < 0)", lambda x: 0.1*(x-5)**2 + 1, "Temperature decreases")
    ]
    
    for ax, (title, func, result) in zip(axes, scenarios):
        T = func(x)
        ax.plot(x, T, 'b-', linewidth=3)
        ax.axhline(T[50], color='r', linestyle='--', alpha=0.5, label='Center point')
        ax.set_title(f'{title} β†’ {result}', fontweight='bold', fontsize=12)
        ax.set_xlabel('Position x')
        ax.set_ylabel('Temperature T')
        ax.grid(True, alpha=0.3)
        ax.legend()
    
    plt.tight_layout()
    plt.show()
    
    print("Heat Equation Intuition:")
    print("  Concave: Heat flows IN β†’ Temperature rises")
    print("  Linear: No curvature β†’ No change")
    print("  Convex: Heat flows OUT β†’ Temperature drops")

visualize_heat_intuition()

Simulating Heat Diffusion: From Equation to CodeΒΆ

To see the heat equation in action, we discretize the spatial domain into a grid of \(n_x\) points and advance the temperature forward in time using a finite difference scheme. The second spatial derivative \(\frac{\partial^2 T}{\partial x^2}\) is approximated by the central difference formula:

\[\frac{\partial^2 T}{\partial x^2} \approx \frac{T_{i+1} - 2T_i + T_{i-1}}{(\Delta x)^2}\]

At each time step, we update the temperature using \(T_i^{new} = T_i + \alpha \frac{\Delta t}{(\Delta x)^2}(T_{i+1} - 2T_i + T_{i-1})\), where \(\alpha\) is the thermal diffusivity. The simulation starts with a β€œhot spot” in the middle of the rod and shows how the temperature profile smooths out over time as heat diffuses outward. This numerical approach – solving a PDE by discretizing it on a grid – is the same idea behind physics-informed neural networks (PINNs), where a neural network learns solutions to PDEs by enforcing the equation as a loss constraint.

def heat_diffusion_demo():
    """Simulate 1D heat diffusion."""
    # Parameters
    L = 1.0  # Length
    nx = 50  # Grid points
    alpha = 0.01  # Thermal diffusivity
    dt = 0.001
    nt = 500
    
    x = np.linspace(0, L, nx)
    dx = L / (nx - 1)
    
    # Initial condition: hot in the middle
    T = np.zeros(nx)
    T[nx//2-5:nx//2+5] = 100
    
    # Store snapshots
    snapshots = [T.copy()]
    times = [0]
    
    for n in range(nt):
        T_new = T.copy()
        for i in range(1, nx-1):
            T_new[i] = T[i] + alpha * dt / dx**2 * (T[i+1] - 2*T[i] + T[i-1])
        T = T_new
        
        if n % 50 == 0:
            snapshots.append(T.copy())
            times.append(n * dt)
    
    # Plot evolution
    fig, ax = plt.subplots(figsize=(12, 6))
    
    for i, (T_snap, t) in enumerate(zip(snapshots[::2], times[::2])):
        alpha_val = 0.3 + 0.7 * i / len(snapshots[::2])
        ax.plot(x, T_snap, alpha=alpha_val, linewidth=2, 
               label=f't = {t:.3f}' if i % 2 == 0 else '')
    
    ax.set_xlabel('Position x', fontsize=12)
    ax.set_ylabel('Temperature T', fontsize=12)
    ax.set_title('Heat Diffusion Over Time', fontweight='bold', fontsize=14)
    ax.legend()
    ax.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.show()
    
    print("Heat diffuses from hot center to cooler edges!")

heat_diffusion_demo()

SummaryΒΆ

The Heat EquationΒΆ

\[ \frac{\partial T}{\partial t} = \alpha \frac{\partial^2 T}{\partial x^2} \]

Key Insight: Curvature in space drives change in time

Next: How to solve this equation!