1.3.3 Drawing Fractals1.3.2 Printing Anagrams1.3 Recursion1.4 Advanced Sorting

1.3.3 Drawing Fractals

Many phenomena in nature have a  fractal (i.e., self-replicated) structure, e.g., the shapes of certain leaves, of feathers, of coast lines, etc. The common characteristics of these shapes is that they are based on a construction principle which is replicated (possibly in a varied form) on a smaller and smaller scale. Such self-replicated shapes can be drawn by recursive methods.

As an example, take the construction principle of an abstract tree depicted in Figure 1.


Tree Construction

The root of the tree is at coordinates (x, y) and it has a stem of length l which grows in angle a from the ground. These units determine an end point (x0, y0) of the stem where two branches emerge which are copies of the tree at a smaller scale. Their stem length l0 is a fraction of l and they are rotated by a fixed angle from the base stem.

A recursive method drawing the tree takes as parameters x, y, a and l and proceeds as follows:

The corresponding code for a Java applet is shown below:

  import java.applet.*;
  import java.awt.*;

  public class Fractal extends Applet
    public void paint (Graphics graph)
      fractal(graph, 200, 300, Math.PI/2, 120);

    void fractal(Graphics graph, int x, int y, double a, double l)
      if (l < 1) return;

      int x0 = x + (int)(l*Math.cos(a));
      int y0 = y - (int)(l*Math.sin(a));
      graph.drawLine(x, y, x0, y0);

      double l0 = l*0.6;
      double a0 = a+Math.PI/4;
      double a1 = a-Math.PI/4;
      fractal(graph, x0, y0, a0, l0);
      fractal(graph, x0, y0, a1, l0);

The applet draws the base stem at coordinates (200,300) with length 120 and angle pi /2 (the angle unit in the trigonometric functions of the Java standard library is in radians, i.e., pi corresponds to 180 degrees).

The method fractal immediately returns if the length of the stem is less than one pixel. Otherwise it computes the coordinates of the end point (x0, y0) using the trigonometric class functions Math.cos and Math.sin (please note that in the Java coordinate system a larger value for the second coordinate means lower points in the plane). The stem length l0 of the branches is computed as 60% of the stem length of the base. The angles a0 and a1 are rotated by 45 degrees in both directions. The two recursive calls then draw the self-replicated tree structures.

We then get the following picture (which is actually the output of the applet):

If you don't see the applet, your Browser does not support Java. Click here, to view a precomputed image.

You must enable Java to see the applet!

© Wolfgang Schreiner; February 3, 2005

1.3.3 Drawing Fractals1.3.2 Printing Anagrams1.3 Recursion1.4 Advanced Sorting