My projects library #4! Gallery Megathread

#61 THE MANDELBROT SET!!!

It took me a lot of tries to complete. I didn’t want to watch the tutorials, since I wouldn’t understand the process. So after watching tons of youtube videos explaining the mandelbrot set, I had finally done it!

Thank you to Crystalize on discord, for showing me a neat way to create complex numbers in processing.
I made all the basic functions I needed with them and commented out the rest. So right now, there are:
addition, subtraction, multiplication ( C * C or C * R ), division ( C / C or C / R), squaring and z^2+c. If you want to use them, feel free!

Code
complex c = new complex(0, 0);
float scale = 150;
int iter = 1000;
float cx = 300, cy = 300;
color clr[] = new color[iter];
color bg = #FF0000;
void setup() {
  size(600, 600);
  colorMode(HSB);
  noStroke();

  float m = 0.95;
  float v = 1;

  for (int i = 0; i < iter; i++) { //can be replaced with: 255 * pow(m,i) and shorten to a single row
    clr[i] = color((v)*255, 255, 255);
    v*=m;
  }
  clr[iter-1] = #000000; //mandelbrot set is black in the center
}

void draw() {
  loadPixels();
  for (float i = 0; i < width; i ++) for (float j = 0; j < height; j++) {
    if (dist(i, j, width*0.5, height*0.5)<scale*2) {
      complex c = new complex( (i-300.0)/scale, (j-300.0)/scale); //og
      complex d = new complex( (i-300.0)/scale, (j-300.0)/scale); //changes

      int it;
      for (it = 0; it < iter-1 && inBounds(d) == true; it++) {
        complex nw = d.z2pc(d, c);
        d.setValueC( nw );
      }
      pixels[(int)i+(int)j*width] = clr[it];
    } else pixels[(int)i+(int)j*width] = bg;
  }
  updatePixels();
  //if(mousePressed) {
  //  println(((float)mouseX-300.0)/scale, ((float)mouseY-300.0)/scale);
  //}
  noLoop();
}

class complex {
  float re, im;
  complex(float re, float im) {
    this.re = re;
    this.im = im;
  }
  void setValue(float re, float im) {
    this.re = re;
    this.im = im;
  }
  void setValueC(complex c) {
    re = c.re;
    im = c.im;
  }
  complex add(complex z) {
    return new complex(re+z.re, im+z.im);
  }
  //complex sub(complex z) {
  //  return new complex(re-z.re, im-z.im);
  //}
  complex multC(complex z) {
    return new complex(re*z.re - im*z.im, re*z.im + z.re * im);
  }
  //complex multR(float z) {
  //  return new complex(re*z, im*z);
  //}
  complex devC(complex z) {
    return new complex( (re*z.re + im*z.im)/(z.re*z.re+z.im*z.im), (im * z.re - re * z.im)/(z.re*z.re+z.im*z.im) );
  }
  complex squ() {
    return multC(this);
  }
  complex z2pc(complex z, complex c) { //f(z) = z^2 + c
    return z.squ().add(c);
  }
}
void printComplex(complex ccc) {
  println("=" + ccc.re + " + " + ccc.im + "i");
}
boolean inBounds(complex c) {
  return(abs(c.re)<2&&abs(c.im)<2);
}

1 Like