Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with my Mandelbrot set code?

Tags:

c

mandelbrot

I'm trying to implement the Mandelbrot set in C, but I'm having a weird problem. My code is as follows:

#include <stdio.h>
#include <math.h>
#include <complex.h>

int iterate_pt(complex c);

int main() {
FILE *fp;
fp = fopen("mand.ppm", "w+");


double crmin = -.75;
double crmax = -.74;
double cimin = -.138;
double cimax = -.75; //Changing this value to -.127 fixed my problem.

int ncols = 256;
int nrows = 256;
int mand[ncols][nrows];
int x, y, color;
double complex c;

double dx = (crmax-crmin)/ncols;
double dy = (cimax-cimin)/nrows;

for (x = 0; x < ncols; x++){
    for (y = 0; y < nrows; y++){
        double complex imaginary = 0+1.0i;
        c = crmin+(x*dx) + (cimin+(y*dy)) * imaginary;
        mand[x][y] = iterate_pt(c);
    }
}

printf("Printing ppm header.");
fprintf(fp, "P3\n");
fprintf(fp, "%d %d\n255\n\n", ncols, nrows);

for (x = 0; x < ncols; x++) {
    for (y = 0; y < nrows; y++){
        color = mand[x][y];
        fprintf(fp, "%d\n", color);
        fprintf(fp, "%d\n", color);
        fprintf(fp, "%d\n\n", color); //Extra new line added, telling the ppm to go to next pixel.
    }
}
fclose(fp);

return 0;
}

int iterate_pt(double complex c){
double complex z = 0+0.0i;
int iterations = 0;
int k;
for (k = 1; k <= 255; k++) {
    z = z*z + c;
    if (sqrt( z*conj(z) ) > 50){
        break;
    }
    else
        ++iterations;
}
return iterations;
}

However, the output of this program, which is stored as a ppm file looks like this:

Converted to a GIF using GIMP. I can confirm that the GIF and original PPM look exactly the same as a PPM and GIF

Thanks for your help!

like image 384
Nathan Jones Avatar asked Oct 20 '11 00:10

Nathan Jones


People also ask

How do you code a Mandelbrot set?

Plot of the Mandelbrot Set Plotting the mandelbrot set is relatively simple: Iterate over all the pixels of your image. Convert the coordinate of the pixel into a complex number of the complex plane. Call the function mandelbrot.

How do you find the number in the Mandelbrot set?

Remember that the formula for the Mandelbrot Set is Z^2+C. To calculate it, we start off with Z as 0 and we put our starting location into C. Then you take the result of the formula and put it in as Z and the original location as C. This is called an iteration.

What real numbers are in the Mandelbrot set?

Fibonacci sequence in the Mandelbrot set Thus, the Fibonacci sequence of 1, 2, 3, 5, 8, 13, and 21 can be found within the Mandelbrot set.

Does the Mandelbrot set end?

The boundary of the Mandelbrot set contains infinitely many copies of the Mandelbrot set. In fact, as close as you look to any boundary point, you will find infinitely many little Mandelbrots.


1 Answers

Try setting cimax to -0.127, I'm also working on this project and it seems to do the trick ;)

like image 175
geekingreen Avatar answered Sep 21 '22 17:09

geekingreen