pad.mattdiesel.co.uk

Snippet - Mandelbrot

Mandelbrot (C++)

Mandelbrot fractal generator for 1b computing
Created 2015-01-26 08:41:11.593090 by Matt.
Modified 2015-01-29 23:24:14.415360 by Matt.

 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
#include <iostream>
#include <fstream>
#include <chrono>

int escape_iterations(double re, double im, int max_iterations) {
	double xre = 0.0, xim = 0.0, rtemp, xre2 = 0.0, xim2 = 0.0;
	int i = max_iterations;

	do {
		--i;
		rtemp = xre2 - xim2 + re;
		xim = 2*xre*xim + im;
		xre = rtemp;
		xre2 = rtemp*rtemp;
		xim2 = xim*xim;
	} while ( (xre2 + xim2 < 4.0f) && i);

	return max_iterations-i;
}


void mandelbrot(std::ostream& os, int w, int h, double startre, double startim, double endre, double endim, int max_iterations) {
	int r, c, iter;
	double zre, zim;
	double stepre = (endre-startre)/w, stepim = (endim-startim) / h;

	int x, y = h;

	os << "P5 " << w << " " << h << " " << max_iterations << "\n";

	for (zim = startim; y; --y) {
		x = w;
		for (zre = startre; x; x--) {
			os << (unsigned char)escape_iterations(zre, zim, max_iterations);
			zre += stepre;
		}
		zim += stepim;
	}
}


int main(int argc, char const *argv[])
{
	std::ofstream ofs("test3.pgm", std::ios::out | std::ios::binary);

	auto start = std::chrono::steady_clock::now();

	mandelbrot(ofs, 10000, 10000, 
						-2.0, -2.0, 2.0, 2.0, 
						255);

	auto end = std::chrono::steady_clock::now();

	std::cout << "Took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;

	return 0;
}