next up previous
Next: An example 1-d solution Up: The diffusion equation Previous: 1-d problem with mixed

An example 1-d diffusion equation solver

Listed below is an example 1-d diffusion equation solving routine which makes use of the Blitz++ library.
// Diffusion1D.cpp

// Function to evolve diffusion equation in 1-d:

//  dT / dt = D d^2 T / dx^2  for  xl <= x <= xh

//  alpha_l T + beta_l dT/dx = gamma_l  at x=xl

//  alpha_h T + beta_h dT/dx = gamma_h  at x=xh

// Array T assumed to be of extent N+2.

// Now, ith element of array corresponds to

//  x_i = xl + i * dx    i=0,N+1

// Here, dx = (xh - xl) / (N+1) is grid spacing.

// Function evolves T by single time-step.

// C = D dt / dx^2, where dt is time-step.

// Uses explicit scheme.

#include <blitz/array.h>

using namespace blitz;

void Diffusion1D (Array<double,1>& T, 
                  double alpha_l, double beta_l, double gamma_l,
                  double alpha_h, double beta_h, double gamma_h,
                  double dx, double C)
{
  // Set N. Declare local array.
  int N = T.extent(0) - 2;
  Array<double,1> T0(N+2);	

  // Evolve T
  T0 = T;	
  for (int i = 1; i <= N; i++)
    T(i) += C * (T0(i-1) - 2. * T0(i) + T0(i+1));

  // Set boundary conditions
  T(0) = (gamma_l * dx - beta_l * T(1)) / (alpha_l * dx - beta_l);
  T(N+1) = (gamma_h * dx + beta_h * T(N)) / (alpha_h * dx + beta_h);
}



Richard Fitzpatrick 2006-03-29