I am trying to create a Mandelbrot set in C code; my output will be a data file, one column of the real parts and one column of the imaginary parts to be plotted in the Argand or complex plane. I have all the complex math stuff defined in a header complex.h
and am using a structure complex
with a double R
for the real part and double I
for the imaginary. I am trying to loop trough values for dz and update z iter=80 number of times, or until the point lies outside a defined radius. dz is imaginary, essentially on a range [(dzrmin + i*dzimin), (dzrmax +i*dzimax)]. z is the current complex number, updated as z^2 = dz + z. I have a function csum()
to sum two complex numbers and a function csquare()
to properly square a complex number. Here is my whole code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "complex.h"
int main(void)
{
double dzrmin, dzrmax, dzimin, dzimax, dzr,dzi, r0,i0, maxrad;
int i,j,k,iter, Ndr,Ndi;
complex z, dz;
dzrmin = -2.1;
dzrmax = 0.6;
dzimin = -1.2;
dzimax = 1.2;
Ndr = 200 ;
Ndi = 180;
dzr = (dzrmax - dzrmin)/Ndr;
dzi = (dzimax - dzimin)/Ndi;
r0 = 0.0;
i0 = 0.0;
z.R = r0;
z.I = i0;
dz.R = dzrmin;
dz.I = dzimin;
maxrad = 2.0;
iter = 80 ;
for(i = 0; i < Ndr; i++ )
{
for(j = 0; j < Ndi; j++ )
{
for(k = 0; k< iter; k++ )
{
printf("%.6lf %.6lf\n", z.R, z.I );
z = csum( csquare( z ), dz ) ;
if( cmag(z) > maxrad) k = iter ;
}
dz.I += dzi ;
}
dz.R += dzr;
z.R = r0;
z.I = i0;
}
return 0;
}
and my header file complex.h
#include <stdlib.h>
#include <math.h>
typedef struct complexnumber{ double R; double I ; } complex ;
double cmag( complex z)
{
return pow( z.R*z.R + z.I*z.I, 0.5 ) ;
}
complex csquare( complex z ) //returns square of a complex
{
complex product ;
product.R = z.R*z.R - z.I*z.I ;
product.I = 2*z.R*z.I ;
return product ;
}
complex csum( complex z1, complex z2) // sums two complex numbers
{
complex sum ;
sum.R = z1.R + z2.R ;
sum.I = z1.I + z2.I;
return sum ;
}
I am getting a few real values, they get very big really quickly and lie outside a radius of 2, followed by a lot of real parts -nan
and imaginary parts -nan
.
Any suggestions as to what I am missing?