simulate heat equation in python

Here is a code snippet that demonstrates how to simulate the heat equation in Python using the finite difference method:

main.py
import numpy as np
import matplotlib.pyplot as plt

# Parameters
L = 1.0  # Length of the rod
T = 0.1  # Total simulation time
k = 1.0  # Thermal diffusivity
dx = 0.01  # Grid spacing
dt = 0.0001  # Time step size
r = k * dt / dx**2  # Stability parameter

# Grid
x = np.arange(0, L + dx, dx)
N = len(x)

# Initial condition
T0 = np.zeros(N)
T0[int(0.4*N):int(0.6*N)] = 1.0

# Main loop
T = T0.copy()
t = 0
while t < T:
    # Compute new temperature
    T[1:-1] += r * (T[2:] - 2*T[1:-1] + T[:-2])

    # Boundary conditions
    T[0] = 0
    T[-1] = 0

    t += dt

# Plot results
plt.plot(x, T0, label='Initial')
plt.plot(x, T, label='Final')
plt.legend()
plt.show()
668 chars
38 lines

This code simulates the heat equation on a 1D rod of length L and computes the temperature at N grid points using the finite difference method. The initial temperature is set to a Gaussian profile, and the simulation is carried out for a duration of T using a time step dt. The results are plotted using Matplotlib.

gistlibby LogSnag