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];
开发者_Go百科 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;
}
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.
Another bug: your function takes int
arguments, so the values of your double
inputs will be truncated (i.e. the fractional part will be discarded).
You should probably be checking for escape inside the while loop. That is to say, if ((a*a + b*b) > 4) at any time then that pixel has escaped, end of story. By continuing to iterate those pixels, as well as wasting CPU cycles you the values are growing without bound and seem to be exceeding what can be represented in a double
- the result is NaN
, so your finaldist computation is producing garbage.
I think you would benefit from more resolution in your main. Your code as you've put it here isn't computing enough pixels to really see much of the set.
精彩评论