This is a code that outputs a .ppm file with the mandelbrot fractal.
How can I optimize this?
#include<bits/stdc++.h>
using namespace std;
int findMandelbrot(double cr, double ci, int max_iterations)
{
int i = 0;
double zr = 0.0, zi = 0.0;
while (i < max_iterations && zr * zr + zi * zi < 4.0)
{
double temp = zr * zr - zi * zi + cr;
zi = 2.0 * zr * zi + ci;
zr = temp;
++i;
}
return i;
}
double mapToReal(int x, int imageWidth, double minR, double maxR)
{
double range = maxR - minR;
return x * (range / imageWidth) + minR;
}
double mapToImaginary(int y, int imageHeight, double minI, double maxI)
{
double range = maxI - minI;
return y * (range / imageHeight) + minI;
}
int main()
{
ifstream f("input.txt");
int imageWidth, imageHeight, maxN;
double minR, maxR, minI, maxI;
if (!f)
{
cout << "Could not open file!" << endl;
return 1;
}
f >> imageWidth >> imageHeight >> maxN;
f >> minR >> maxR >> minI >> maxI;
ofstream g("output_image.ppm");
g << "P3" << endl;
g << imageWidth << " " << imageHeight << endl;
g << "255" << endl;
double start = clock();
for (int i = 0; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth; j++)
{
double cr = mapToReal(j, imageWidth, minR, maxR);
double ci = mapToImaginary(i, imageHeight, minI, maxI);
int n = findMandelbrot(cr, ci, maxN);
int r = ((int)sqrt(n) % 256);
int gr = (2*n % 256);
int b = (n % 256);
g << r << " " << gr << " " << b << " ";
}
g << endl;
if(i == imageHeight / 2) break;
}
cout << "Finished!" << endl;
double stop = clock();
cout << (stop-start)/CLOCKS_PER_SEC;
return 0;
}
I go until imageHeight / 2 because in photoshop I can just copy the other half.
I was thinking about logarthmic power but tried something and only works with integers...
At the end I am showing the time it takes to run some data. I tried some things from the internet but nothing really worked out or maybe I didn't how to put it right..
this is the output with the following input: 512 512 512 -1.5 0.7 -1.0 1.0
and it took 0.315s to produce this.