Skip to content

Instantly share code, notes, and snippets.

@foota
Created May 13, 2012 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foota/2689086 to your computer and use it in GitHub Desktop.
Save foota/2689086 to your computer and use it in GitHub Desktop.
Tetration fractal (C++ with TBB)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <sys/time.h>
#include "tbb/task_scheduler_init.h"
#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"
#include "tbb/tick_count.h"
using namespace std;
using namespace tbb;
const double PI = 3.1415926535897931;
// Tetration fractal
class Tetration {
private:
float l, t, w, h;
int sw, sh, mit;
vector<int>& data;
public:
// left, top, width , height, screen width, screen height, max iterations, data[sw*sh]
Tetration(float l, float t, float w, float h, int sw, int sh, int mit, vector<int>& data)
: l(l), t(t), w(w), h(h), sw(sw), sh(sh), mit(mit), data(data) { }
void operator()(const blocked_range<int>& r) const {
for (int n = r.begin(); n != r.end(); n++) {
float x = l + w * (n % sw) / (sw - 1);
float y = t + h * (n / sw) / (sh - 1);
int i = 0;
for (; i < mit - 1; i++) {
float e = exp(-0.5 * PI * y);
if (e != e) break;
float p = PI * x * 0.5;
x = e * cos(p);
y = e * sin(p);
if (x * x + y * y > 1e12) break;
}
data[n] = i;
}
}
};
int main(int argc, char* argv[])
{
if (argc < 6) {
cerr << "Usage: " << argv[0] << " outfile left top width height [screen_width=512 screen_height=512 max_iters=256]" << endl;
cerr << " Ex. " << argv[0] << " tetration.out -1.5 0.0 0.75 0.75" << endl;
exit(1);
}
task_scheduler_init init;
fstream fs(argv[1], ios_base::out);
float l = atof(argv[2]);
float t = atof(argv[3]);
float w = atof(argv[4]);
float h = atof(argv[5]);
int sw = 512;
int sh = 512;
int mit = 256;
if (argc >= 7) sw = atoi(argv[6]);
if (argc >= 8) sh = atoi(argv[7]);
if (argc >= 9) mit = atoi(argv[8]);
vector<int> data(sw * sh);
cout << "Range: (" << l << ", " << t << ") - (" << l + w << ", " << t + h << ")" << endl;
cout << "Image: " << sw << " x " << sh << endl;
cout << "Max number of iterations: " << mit << endl;
tick_count start_time = tick_count::now();
parallel_for(blocked_range<int>(0, sw * sh), Tetration(l, t, w, h, sw, sh, mit, data), auto_partitioner());
cout << "Time: " << (tick_count::now() - start_time).seconds() << endl;
// output data
int cnt = 0;
fs << sw << " " << sh << endl;
for (vector<int>::iterator p = data.begin(); p != data.end(); ++p, cnt++) {
fs << *p << " ";
if ((cnt + 1) % sw == 0) fs << endl;
}
return 0;
}
@foota
Copy link
Author

foota commented May 14, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment