Mandelbrot set: Difference between revisions
Content added Content deleted
No edit summary |
(→{{header|C}}: A note about the C code, added C++) |
||
Line 5: | Line 5: | ||
=={{header|C}}== |
=={{header|C}}== |
||
{{works with|gcc}} |
{{works with|gcc}} |
||
This code assumes there exists a function DrawPixel taking as arguments the x and y position, followed by the red, green and blue components of the color. Note that this function is not part of standard C. |
|||
<lang C> |
<lang C> |
||
#define MAX_ITERATIONS 500 |
#define MAX_ITERATIONS 500 |
||
Line 32: | Line 33: | ||
} |
} |
||
} |
} |
||
} |
|||
</lang> |
|||
=={{header|C++}}== |
|||
This generic function assumes that the image can be accessed like a two-dimensional array of colors. It may be passed a true array (in which case the Mandelbrot set will simply be drawn into that array, which then might be saved as image file), or a class which maps the subscript operator to the pixel drawing routine of some graphics library. In the latter case, there must be functions get_first_dimension and get_second_dimension defined for that type, to be found by argument dependent lookup. The code provides those functions for built-in arrays. |
|||
<lang cpp> |
|||
#include <cstdlib> |
|||
#include <complex> |
|||
// get dimensions for arrays |
|||
teplate<typename ElementType, std::size_t dim1, std::size_t dim2> |
|||
std::size_t get_first_dimension(ElementType (&a)[dim1][dim2]) |
|||
{ |
|||
return dim1; |
|||
} |
|||
teplate<typename ElementType, std::size_t dim1, std::size_t dim2> |
|||
std::size_t get_second_dimension(ElementType (&a)[dim1][dim2]) |
|||
{ |
|||
return dim2; |
|||
} |
|||
template<typename ColorType, typename ImageType> |
|||
void draw_Mandelbrot(ImageType& image, // where to draw the image |
|||
ColorType set_color, ColorType non_set_color, // which colors to use for set/non-set points |
|||
double cxmin, double cxmax, double cymin, double cymax, // the rectangle to draw in the complex plane |
|||
unsigned int max_iterations) // the maximum number of iterations |
|||
{ |
|||
std::size_t const ixsize = get_first_dimension(ImageType); |
|||
std::size_t const iysize = get_first_dimension(ImageType); |
|||
for (std::size_t ix = 0; ix < ixsize; ++ix) |
|||
for (std::size_t iy = 0; iy < iysize; ++iy) |
|||
{ |
|||
std::complex c(cxmin + ix/(ixsize-1.0)*(cxmax-cxmin), cymin + iy/(iysize-1.0)*(cymax-cymin)); |
|||
std::complex z = 0; |
|||
unsigned int iterations = 0; |
|||
while (iterations < max_iterations && std::norm(z) < 4.0) // note: std::norm(z) gives the *squared* absolute value of z |
|||
{ |
|||
z = z*z + c; |
|||
++iterations; |
|||
} |
|||
if (iterations == max_iterations) |
|||
image[ix][iy] = set_color; |
|||
else |
|||
image[ix][iy] = non_set_color; |
|||
} |
|||
} |
} |
||
</lang> |
</lang> |