Mandelbrot set

This is a Manblebrot set. Which is a fractal based on the complex plane.

Log in to post a comment.

// You can find the Turtle API reference here: https://turtletoy.net/syntax
const res = 400; //min=50, max=500, step=50
const max_itter = 50; //min=50, max=500, step=50
const offsetX = -.5; //min=-1, max=1, step=0.01
const offsetY = 0; //min=-1, max=1, step=0.01
const zoom = 1; //min=1, max=200, step=1
const lineSize = 1; //min=1, max=10, step=1

Canvas.setpenopacity(1);

// Global code will be evaluated once.
const turtle = new Turtle();

// The walk function will be called until it returns false.
function walk(i) {
    // I borrowed this from this post: https://turtletoy.net/turtle/7a0b879dab
    // This gave me the coordinates
    const f = Math.floor(i/res);
    const d = Math.ceil(i/2)*4-i*2-1;
    const x = (i-f*res)/(res-1)*200-100;
    const y = f/(res-1)*200-100;
    
    // I remap the coordinates from -100:100 to - 1:1 but this can chnage based on the offset and zoom level
    const nx = x/100/zoom+offsetX;
    const ny = y/100/zoom+offsetY;
    
    // simple mandlebrot set calculation you can find more info here: https://en.wikipedia.org/wiki/Mandelbrot_set
    let zx = 0;
    let zy = 0;
    let itter = 0;
    while(zx*zx+zy*zy < 2 && itter < max_itter)
    {
        let xTemp = (zx*zx)-(zy*zy)+nx;
        zy = 2*zx*zy+ny;
        zx = xTemp;
        itter++;
    }
    
    // calculate the size of the linesegment based on how many itteration there are on this point
    const size = (itter/max_itter)*lineSize;
    turtle.jmp(x,y);
    // calculate the endpoint of the line based on the size of the linesegment 
    // and the angle of the last point of the calculation (zx, zy)
    let _x = zx - nx;
    let _y = zy - ny;
    let len = Math.sqrt(_x*_x+_y*_y);
    if(len != 0)
    {
        turtle.goto(x+(_x/len)*size, y+(_y/len)*size);
    }
    return i < res*res;
}