How to program a fractal?

后端 未结 14 973
花落未央
花落未央 2020-12-04 05:34

I do not have any experience with programming fractals. Of course I\'ve seen the famous Mandelbrot images and such.

Can you provide me with simple algorithms for fra

14条回答
  •  情歌与酒
    2020-12-04 05:59

    You should indeed start with the Mandelbrot set, and understand what it really is.

    The idea behind it is relatively simple. You start with a function of complex variable

    f(z) = z2 + C

    where z is a complex variable and C is a complex constant. Now you iterate it starting from z = 0, i.e. you compute z1 = f(0), z2 = f(z1), z3 = f(z2) and so on. The set of those constants C for which the sequence z1, z2, z3, ... is bounded, i.e. it does not go to infinity, is the Mandelbrot set (the black set in the figure on the Wikipedia page).

    In practice, to draw the Mandelbrot set you should:

    • Choose a rectangle in the complex plane (say, from point -2-2i to point 2+2i).
    • Cover the rectangle with a suitable rectangular grid of points (say, 400x400 points), which will be mapped to pixels on your monitor.
    • For each point/pixel, let C be that point, compute, say, 20 terms of the corresponding iterated sequence z1, z2, z3, ... and check whether it "goes to infinity". In practice you can check, while iterating, if the absolute value of one of the 20 terms is greater than 2 (if one of the terms does, the subsequent terms are guaranteed to be unbounded). If some z_k does, the sequence "goes to infinity"; otherwise, you can consider it as bounded.
    • If the sequence corresponding to a certain point C is bounded, draw the corresponding pixel on the picture in black (for it belongs to the Mandelbrot set). Otherwise, draw it in another color. If you want to have fun and produce pretty plots, draw it in different colors depending on the magnitude of abs(20th term).

    The astounding fact about fractals is how we can obtain a tremendously complex set (in particular, the frontier of the Mandelbrot set) from easy and apparently innocuous requirements.

    Enjoy!

提交回复
热议问题