Search code examples
cfunctionasciimandelbrot

Code help to determine if point is in Mandelbrot set (check my solution)


Here is my function that tests two points x and y if they're in the mandelbrot set or not after MAX_ITERATION 255. It should return 0 if not, 1 if it is.

int isMandelbrot (int x, int y) {


    int i;
    int j;
    double Re[255];
    double Im[255];
    double a;
    double b;
    double dist;
    double finaldist;
    int check;

    i=0;
    Re[0]=0;
    Im[0]=0;
    j=-1;
    a=0;
    b=0;

    while (i < MAX_ITERATION) {

        a = Re[j];
        b = Im[j];

        Re[i]=((a*a)-(b*b))+x;
        Im[i]=(2 * a * b) + y;

        i++;
        j++;
    }

    finaldist = sqrt(pow(Re[MAX_ITERATION],2)+pow(Im[MAX_ITERATION],2));

    if (dist > 2) { //not in mandelbrot
        check = 0;
    } else if (dist <= 2) { //in mandelbrot set
        check = 1;
    }

    return check;
}

Given that it's correct (can someone verify... or write a more efficient one?). Here is my code to print it, however it does not work! (it keeps giving all points are in the set). What have I done wrong here?

int main(void) {

    double col;
    double row;

   int checkSet;

    row = -4;
    col = -1;

    while (row < 1.0 ) {
        while (col < 1.0) {
        checkSet = isMandelbrot(row, col);
            if (checkSet == 1) {
                printf("-");
            } else if (checkSet == 0) {
                printf("*");
            }
            col=col+0.5;
        }
        col=-1;
        row=row+0.5;
        printf("\n");
    }
return 0;
}

Solution

  • There are some bugs in your code. For example, you do this:

    a = Re[j];
    b = Im[j];
    

    But at the first iteration, j = -1, so you're getting the value at index -1 of the arrays. That is not what you wanted to do.

    Also, why are Re and Im arrays - do you really need to keep track of all the intermediate results in the calculation?

    Wikipedia contains pseudocode for the algorithm, you might want to check your own code against that.