Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Sure, here is an example of solving the one-dimensional diffusion equation using Python and

discretization:

First, let's define the problem we want to solve. We want to find the temperature distribution in a
thin rod of length L, with an initial temperature distribution T(x,0) = f(x) and boundary conditions
T(0,t) = T(L,t) = 0. The diffusion equation that describes this problem is:

∂T/∂t = α ∂²T/∂x²

where α is the thermal diffusivity of the material.

We can discretize this equation using the finite difference method. Let's use the forward difference
for the time derivative and the centered difference for the space derivative. Let's also assume that
the time step Δt and the space step Δx are constant. Then, the discretized equation is:

(T_i,j+1 - T_i,j)/Δt = α (T_i-1,j - 2T_i,j + T_i+1,j)/(Δx)²

where T_i,j represents the temperature at point i and time j.

We can rearrange this equation to solve for T_i,j+1:

T_i,j+1 = T_i,j + α Δt/(Δx)² (T_i-1,j - 2T_i,j + T_i+1,j)

Now, let's implement this equation in Python. We will use the numpy library to create arrays for the
temperature distribution and to perform the calculations.

import numpy as np

import matplotlib.pyplot as plt

# Define the parameters

L = 1.0 # length of the rod

N = 100 # number of grid points

dx = L/(N-1) # grid spacing

alpha = 1.0 # thermal diffusivity

T0 = np.zeros(N) # initial temperature distribution

T0[0] = 1.0 # set the left boundary temperature

T0[N-1] = 0.0 # set the right boundary temperature

t_max = 1.0 # maximum simulation time

dt = 0.001 # time step

# Create the grid


x = np.linspace(0, L, N)

# Initialize the temperature distribution

T = T0.copy()

# Time loop

t = 0.0

while t < t_max:

# Calculate the new temperature distribution

T[1:N-1] = T[1:N-1] + alpha*dt/(dx**2) * (T[0:N-2] - 2*T[1:N-1] + T[2:N])

# Apply the boundary conditions

T[0] = 1.0

T[N-1] = 0.0

# Update the time

t = t + dt

# Plot the temperature distribution

plt.plot(x, T)

plt.xlabel('x')

plt.ylabel('Temperature')

plt.show()

In this code, we first define the parameters of the problem, including the length of the rod, the
number of grid points, the thermal diffusivity, the initial temperature distribution, the maximum
simulation time, and the time step. We then create the grid and initialize the temperature
distribution. We use a while loop to update the temperature distribution at each time step using the
discretized diffusion equation. We apply the boundary conditions at each time step by setting the
temperature at the left and right boundaries to their prescribed values. Finally, we plot the
temperature distribution as a function of position.

This code can be used to solve the one-dimensional diffusion equation for different initial
temperature distributions and boundary conditions by changing the parameters in the code. The key
to discretizing

You might also like