On the first page of the book Superfractals is one of those cool mathematical curiosities that makes math geeks like me go all Archimedian. (No, I didn’t run naked to the bookstore counter and buy the book. But I did go home and order it at Amazon.)
Here’s the gist of the curiosity, which I created an algorithm for below:
Pick 3 points on the xy-plane and label them A, B, and C. (As a group I’ll call them ABC.)
Now pick a fourth point and label it X0. Now randomly pick a point from the ABC group. From X0 make a new point that is the mid-point between your random ABC selection and X0. Label that point X1.
Now from X1 do the same thing again. Pick randomly between ABC group and then from X1 go to the mid-point between X1 and your random selection.
Repeat that a few millions times.
You might think that eventually you’ll fill up the points in between the ABC group and have a solid triangle. But no. You’ll end up with a skewed Sierpinski triangle as you can see below.
Serendipitous errors
In my first version of the algorithm I made a mistake in the equation that calculates the mid-point. The equation should be as such:
xmid = ( x1 + x2 ) / 2
And the same for the y-coordinate.
In my haste I wrote the incorrectly and calculated a difference instead of a sum between the two values.
Now that sould produce something random because what on earth could the relationship of the difference between the first and second points divided by two have anything to do with?
But you don’t get a random dispersion. You get something that closely resembles the inverse of the Kosh snowflake. Why? Ask a mathematician because I have no idea.
Grdenizing the code
This is exactly the sort of algorithm where code optimization can make a big difference. John Grden just wrote a wonderful post on optimizing Actionscript by using bitwise operations and a few other tricks that I applied here.
In the application above you can check/uncheck the optimized code checkbox to select which version of the method gets used. Then you can see the results displayed and judge for yourself how much code optimization can benefit you in cases where you are iterating over large sets of data.
View source code here.
The obvious place to optimize is with the mid-point equation. Instead of dividing by two I’m using the equivalent bitwise operation: >> 1.
That helped but using int(num) instead of Math.floor(num) made a huge difference. I’ll never use Math.floor() again that’s for sure.
If something here has proved valuable to you then feel free to drop a couple of bucks in the tip-jar.
