Wednesday, 15 July 2015

The Heat Equation: a Python implementation

By making some assumptions, I am going to simulate the flow of heat through an ideal rod.
Suppose you have a cylindrical rod whose ends are maintained at a fixed temperature and is heated at a certain x for a certain interval of time. Suppose that the temperature in each section with infinitesimal width dx is uniform so that we can describe the temperature in the rod using a function of only x and t.

Mathematically speaking, problem we are now facing is the following:


where k is a constant called thermal diffusivity and is different according to the different materials. By using the method of separation of variables, we can find the solution we need and by applying the initial conditions we find a particular solution for f(x) = sin(x) and L = pi
Our solution looks something like this:
Now we only need to evaluate our function at each x and t. Remember that if u(x,y) is differentiable, then:


holds. We can throw out the last term and approximate our function using the above relation since partial derivatives of u must exists and we can easily get them. Thinking about it, the second term is useless too, since we are not moving along the x axis, therefore we are left with the following:


By using matplotlib and the animation function I generated this short clip:

Here is the python implementation of the solution and the code used to graph the solution evolving with time.

Hope this was useful!


  1. Hello, maybe I'm wrong but it seems to me that the function u(x0, t0) it is already exponentially damped since t0 is increasing in the for cycle and it is argument of u(x0, t0). Why you add the gradient? This should be added to a fixed initial value...please let me know what do you think...

    1. my opinion is that you do not need the gradient at all since you already know the time dependent solution...

  2. what needs to be change, if my boundary condition is not fixed at x=0 ?