Download c source code

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>

#define WIDTH      1000
#define HEIGHT     1000
#define EPSILON    0.01

static double temperature[HEIGHT+2][WIDTH+2];
static double prev_temperature[HEIGHT+2][WIDTH+2];

void initialize(void);
void track_progress(int iter);

int main(void)
{
	int iteration = 1;
	double worst_dt = 100.0;

	struct timeval start_time, stop_time, elapsed_time;
	gettimeofday(&start_time,NULL);

	initialize();

	while ( worst_dt > EPSILON )
	{
		for(int i = 1; i <= HEIGHT; i++)
		{
			for(int j = 1; j <= WIDTH; j++)
			{
				temperature[i][j] = 0.25 * (prev_temperature[i+1][j] + prev_temperature[i-1][j] +
						prev_temperature[i][j+1] + prev_temperature[i][j-1]);
			}
		}

		worst_dt = 0.0;

		for(int i = 1; i <= HEIGHT; i++)
		{
			for(int j = 1; j <= WIDTH; j++)
			{
				worst_dt = fmax( fabs(temperature[i][j]-prev_temperature[i][j]), worst_dt);
				prev_temperature[i][j] = temperature[i][j];
			}
		}

		if((iteration % 100) == 0)
			track_progress(iteration);

		iteration++;
	}

	gettimeofday(&stop_time,NULL);
	timersub(&stop_time, &start_time, &elapsed_time);

	printf("\nMax error at iteration %d was %f\n", iteration-1, worst_dt);
	printf("Total time was %f seconds.\n", elapsed_time.tv_sec+elapsed_time.tv_usec/1000000.0);
}

void initialize()
{
	for(int i = 0; i <= HEIGHT+1; i++)
		for (int j = 0; j <= WIDTH+1; j++)
			prev_temperature[i][j] = 0.0;

	for(int i = 0; i <= HEIGHT+1; i++)
	{
		prev_temperature[i][0] = 0.0;
		prev_temperature[i][WIDTH+1] = (100.0/HEIGHT)*i;
	}

	for(int j = 0; j <= WIDTH+1; j++)
	{
		prev_temperature[0][j] = 0.0;
		prev_temperature[HEIGHT+1][j] = (100.0/WIDTH)*j;
	}
}

void track_progress(int iteration)
{
	printf("---------- Iteration number: %d ------------\n", iteration);
	for(int i = HEIGHT-5; i <= HEIGHT; i++)
		printf("[%d,%d]: %5.2f  ", i, i, temperature[i][i]);

	printf("\n");
}