Mandelbrot Set

mandelbrot

bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();

  cr->set_line_width(1.0);
 
  double x_min =  -1.5;
  double x_max =   0.5;
  double y_min =  -1.0;
  double y_max =   1.0;
  double large =  10.0;
  int    kmax  = 500;

  for(int i=0;i<width;i++) {
	  for(int j=0;j<height;j++) {
		  double x=x_min+(x_max-x_min)*(double)i/(double)width;
		  double y=y_min+(y_max-y_min)*(double)j/(double)height;
		  complex<double> z=0.0;
		  complex<double> w=complex<double>(x,y);
		  int count=0;
		  for(int k=0;k<kmax;k++) {
			  z=z*z+w;
			  if(abs(z)>large) {
				  count = k;
				  break;
			  }
		  }
		  if(count) {
			  cr->set_source_rgba(0.9,(count%10)/10.0,0.3,1.0);
		  } else {
			  cr->set_source_rgba(0.0,0.2,0.7,1.0);
		  }
		  cr->rectangle((double)i, (double)j, 1.0, 1.0);
		  cr->stroke();
	  }
  }
  return true;
}