## Chaos Game and Fractals

For the discussion of math. Duh.

Moderators: gmalivuk, Moderators General, Prelates

### Chaos Game and Fractals

Hi All,

I am trying to write a MatLab program that runs a chaos game to generate fractals (or not).

Information found here: http://mathworld.wolfram.com/ChaosGame.html

I've used the n=3 r=1/2 chaos game before to generate the Sierpinski triangle, even on my TI-83. Now I'm working on a MatLab program to run the chaos game for arbitrary n and r values. Can someone take a look at my code and help me find where I went wrong? The code is verified to generate the Sierpinski triangle when n=3 r=1/3, but I can not generate any of the fractals mentioned in the website above.

My m-file:

Code: Select all
`clear all;n=4;r=1/(n-1);t=5000;Ax = 2*pi/n;Ai = pi-Ax;Vx = zeros(1,n+1);Vy = zeros(1,n+1);Vx(1) = 0;Vy(1) = 0;Vx(2) = 1;Vy(2) = 0;for i=3:n+1    Axn = Ax*(i-2);    Vx(i) = Vx(i-1)+cos(Axn);    Vy(i) = Vy(i-1)+sin(Axn); endSx=0;Sy=0;for i=1:n    Sx = Sx + Vx(i);    Sy = Sy + Vy(i);endCx = Sx/n;Cy = Sy/n;Nx = zeros(1,t);Ny = zeros(1,t);Nx(1) = Cx+Cy*(rand(1)-.5);Ny(1) = Cy+Cy*(rand(1)-.5);for i=2:t    D = rand(1)    for j=1:n        if ((j-1)/n < D)&&(D < j/n)            Nx(i) = Nx(i-1)+r*(Vx(j)-Nx(i-1))            Ny(i) = Ny(i-1)+r*(Vy(j)-Ny(i-1))            plot (Vx,Vy,Cx,Cy,Nx,Ny,'.');            xlim([min(Vx) max(Vx)])            ylim([min(Vy) max(Vy)])            drawnow        end    endend%plot (Vx,Vy,Cx,Cy,Nx,Ny,'.');`
gomgabbar

Posts: 2
Joined: Fri Apr 13, 2012 1:25 am UTC

### Re: Chaos Game and Fractals

Nothing glaring, but I am not familiar with the algorithm. However, is this intended?

Nx(1) = Cx+Cy*(rand(1)-.5);
gorcee

Posts: 1501
Joined: Sun Jul 13, 2008 3:14 am UTC
Location: Charlottesville, VA

### Re: Chaos Game and Fractals

gorcee wrote:Nothing glaring, but I am not familiar with the algorithm. However, is this intended?

Nx(1) = Cx+Cy*(rand(1)-.5);

Ah, glad you asked. I needed to pick a staring place inside an n sided regular polygon. (Cx, Cy) is the Cartesian coordinate for the center, and because the base is always along the x-axis, Cy is also the smallest distance from the edge to the side. Thus, I take the center point, and add (or subtract) at most one half of this distance (in each coordinate) so that the starting point for the algorithm will be a random point, guaranteed to be inside the polygon.

As an update from the original post, I have found the error in my original code. I took r as the distance from the current point toward the selected vertex, when r is actually taken as the distance from the selected vertex to the current point. These two have the same result if r is 1/2; that is why the Sierpinski triangle rendering worked. To update my code, I simply replaced instances of r with (1-r) and it now works for all Sierpinski-like chaos games
gomgabbar

Posts: 2
Joined: Fri Apr 13, 2012 1:25 am UTC