Download c source code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#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");
}