%% Script to implement the Chaos Game, as described in Chapter 5 of %% 'Chaos and Order in the Capital Markets,' 2nd ed, by Edgar Peters. %% This is based on Iterated Function Systems (IFS), created by %% Michael Barnsley of Iterated Systems. %% %% This script draws an equilateral triangle, with side length 2. It %% picks a random point within that triangle, then starts iterating %% according to the rule: at each step, randomly pick one of the %% triangle's 3 vertices, and move the current point halfway toward %% the chosen vertex. Repeat for the next step. %% %% The attracting set of points will be the Sierpinski triangle. Note %% it might not come out so clearly from this script, since Matlab draws %% its points kind of big. I didn't worry too much about this, since %% I just wrote this script to play around with this system. %% %% Ken Gosier %% October 2000 %% Seed random number generator with time rand('state', sum(100*clock)); %% Random point in box (0,1) x (0,sqrt(3)). If in upper half of box, %% reflect down to right half of triangle pt.x = rand; pt.y = rand*sqrt(3); if pt.y > 2*pt.x pt.x = 2 - pt.x; pt.y = sqrt(3) - pt.y; end %% plot equilateral triangle bounding Sierpinski bottom_x = [0, 2]; bottom_y = [0, 0]; sides_x = [0, 1, 2]; sides_y = [0, sqrt(3), 0]; % statements needed so later points will go on same plot as triangle close all; figure; hold on; plot(bottom_x, bottom_y, '-', sides_x, sides_y, '-'); xmin = 0; xmax = 2; ymin = 0; ymax = sqrt(3); axis([ xmin xmax ymin ymax ]); %% 3 vertices of trangle pt1.x = 0; pt1.y = 0; pt2.x = 2; pt2.y = 0; pt3.x = 1; pt3.y = sqrt(3); vertarr = [pt1, pt2, pt3]; %% start iterating. %% %% threshold tells, after what iteration do we start plotting points? %% In this system, we expect our distance to the attractor to shrink %% by 1/3 with each iteration. So I choose threshold=5, it will be %% 1/243-rd its original distance from the attractor. And Matlab %% draws its points kind of big, so it will probably be close enough %% for displaying. %% %% ask_iter tells, how many iterations between stopping to ask the %% user to continue or quit? It's a kludge to say 'Press Ctrl-C to %% stop,' but this script is just for playing around with this system; %% I'll leave the gorgeous UI for the commercial release. iter = 0; threshold = 5; ask_iter = 1000; while 1 %% point to move toward sub = fix(rand*3) + 1; pt.x = 0.5*(pt.x + vertarr(sub).x); pt.y = 0.5*(pt.y + vertarr(sub).y); %% plot if past threshold, ask to stop if %% right multiple iter = iter + 1; if iter > threshold plot(pt.x, pt.y, '.'); end if mod(iter,ask_iter) == 0 input('Press RETURN to go on, Ctrl-C to stop:'); % user has to activate the command window to press RETURN. This % makes the plot window active again H = gcf; figure(H); end end