Solving Partial Differential Equations with Numpy and Scipy: a Step-by-step Approach

Partial differential equations (PDEs) are fundamental in modeling various physical phenomena, such as heat transfer, wave propagation, and fluid dynamics. Using Python libraries like NumPy and SciPy simplifies the process of solving these equations numerically. This article provides a step-by-step approach to solving PDEs with these tools.

Setting Up the Problem

Begin by defining the PDE and the domain. For example, consider the one-dimensional heat equation:

∂u/∂t = α ∂²u/∂x²

Specify initial conditions, boundary conditions, and parameters such as thermal diffusivity α.

Discretizing the Domain

Divide the spatial domain into discrete points using NumPy arrays. For example, create a grid of points:

import numpy as np

x = np.linspace(0, 1, 100)

Set the time step and total simulation time to control the numerical stability and accuracy.

Implementing the Numerical Method

Use finite difference methods to approximate derivatives. For the heat equation, an explicit scheme updates the temperature at each point:

u_new = u + r * (u[i+1] – 2*u[i] + u[i-1])

where r is a stability parameter calculated as α * dt / dx².

Running the Simulation

Iterate over time steps, updating the solution array at each iteration. Use NumPy operations for efficiency:

for n in range(steps):

  u[1:-1] = u[1:-1] + r * (u[2:] – 2*u[1:-1] + u[:-2])

Apply boundary conditions after each update to maintain the problem constraints.

Visualizing Results

Use libraries like Matplotlib to visualize the temperature distribution over time. Plot the initial and final states to observe the diffusion process.

Example code:

import matplotlib.pyplot as plt

plt.plot(x, u)