# Category Archives: Programming

## Pythagorean Tree

Many, many years ago I came up with an idea about a fractal that would be based on right triangles and squares. People that had less mathematical experience than I, didn’t take me seriously, when I told about my idea. They thought that this was just some kind of nonsense.

I didn’t visualize my idea and forgot the whole thing… Later, after many years when I started to read e-books about fractals, I found sophisticated ideas how to make nice colored Pythagorean fractal trees. I think I’ve been dealing with wrong people in the past… 🙂

This article discusses only about simplest possible Pythagorean fractal tree, most symmetrical version of it.

We start with a right triangle with two 45 degrees angles and one 90 degrees angle and visually speaking turn the triangle so that hypotenuse is at the bottom: Next we draw squares against the sides of the triangle so that the length of the side of the square is the length of the side of the triangle: Next we imagine new right triangles to the farthest side of the ”branch” squares and do the same process as earlier: We draw squares to all the sides of the triangles.

This process is continued infinitely and we have a fractal! …that looks like a tree. The length of the new hypotenuse c‘ = cos(45°) * c, where c is the length of the hypotenuse of previous iteration loop’s right triangle(s).

When generating the tree, I recommend using Java with JavaFX package or using JavaScript, because with those one can use the following methods:

• beginPath
• translate
• rotate
• save
• restore

These methods make it quite easy to generate a fractal tree. When drawing the tree into screen, only the squares are drawn.

The e-book below discusses lots of fractal programming and has also an example codes in JavaScript generating these kinds of trees (also colored):  ## Generating the Cantor’s Set with Computer

The Cantor’s set is somewhat fascinating fractal, when one gets to more familiar with it.

The basic idea is to handle real number interval [0,1]. This is divided to three parts of same width removing the middle part. The remaining parts are again divided to three parts of same width removing always the middle part. This is continued infinitely.

The Cantor’s set consists of the points that are left in this process.

In the language of the set theory the Cantor’s set can be expressed as follows: The union tells what doesn’t belong to the set.

I have used this formula to implement the Cantor’s set in my program. The idea is to examine the union interval and draw a pixel, when the point does belong to the set.

Below is a picture from the program’s output: Here’s the Java program in full:

```import java.awt.*;
import javax.swing.*;
import java.awt.event.WindowEvent;
import java.lang.Math;

public class Cantor {

private JFrame frame;
private CantorPanel panel;

public Cantor() {
frame = new JFrame("The Cantor's Set");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initialize();
frame.pack();
frame.setVisible(true);
}

private void initialize() {
panel = new CantorPanel();
}

public static void main(String args[]) {
new Cantor();
}
}

class CantorPanel extends JPanel {

public CantorPanel() {

setBackground(Color.lightGray);
setPreferredSize(new Dimension(1024,100));
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;

drawCantor(g, 7);
}

public void drawCantor(Graphics g, int maxIter) {

int y = 17;

for (int m = 1; m < maxIter + 1; m++) {

for (int x = 0; x < 1024; x++) {

if (belongsToSet(m,x) == true) g.drawOval(x,y,1,1);
}
y = y + 10;
}
}

public boolean belongsToSet(int m, double x) {

double line = 1024;
double x1,x2;

for(int mm = 1; mm < m ; mm++) {

for (int k = 0; k < (int)((Math.pow(3,(mm-1))) - 1 + 1); k++) {

x1 = (3.0*k + 1) / Math.pow(3.0,mm);
x2 = (3.0*k + 2) / Math.pow(3.0,mm);

if ((x > x1 * line) && (x < x2 * line)) return false;

}

}
return true;
}

}
```

Because of the calculation precision with “big” number of iterations drawing accuracy isn’t very good.

The program is free for personal and educational use.

On Georg Cantor ## How to determine the number of digits in a number

Mathematically the number of digits in given integer > 0 can be determined with logarithm.

The number of digits in an integer > 0 is

Trunc(Logk(number)) + 1

Trunc comes from the Pascal programming language and means truncation. ”number” is 10 base system number of k base system number.

The idea is to examine how many powers of base system k there is in the number, that is how many times the given number can be divided with the base number until we get number < 1. With this our friend logarithm helps us to determine that. As a reminder, logarithm is reverse operation to power.

Examples:

In 10 base system in number 12345678 there is 7 powers of 10: Trunc(Log1012345678) = 7, the number of digits is 7 + 1 = 8.

The hexdecimal system number 99916 = 245710, Log16 2457 = 2.8156…, the number of digits is 2 + 1 = 3.

Hex number FF16 = 25510, Log16 255 = 1.9985…, the number of digits is 1 + 1 = 2.

Binary number (k = 2) 100000002 = 128, Log2 128 = 7, the number of digits is 7 + 1 = 8.

Binary number 101000012 = 16110, Trunc(Log2 161) = Trunc(7.33091…) = 7, the number of digits is 7 + 1 = 8. Image courtesy of Stuart Miles at FreeDigitalPhotos.net

Via programming the number of digits can be determined by dividing the number by the base system number k until the number being divided is < 1. Now the number of digits is the number of divisions.

Below is a C programming language program that determines the number digits of 10 base system number that can be positive or negative decimal number:

```#include <stdio.h>
#include <math.h>

int detDigits(double);

void main(void) {

double decimalnumber;
int number_of_digits;

printf("Give a decimal number: ");
scanf("%lf", &decimalnumber);

number_of_digits = detDigits(decimalnumber);

printf("The number of digits is %d.",number_of_digits);

}

int detDigits(double dn) {

int digits_integer_part, digits_decimal_part;
int worknumber;

if (dn == 0) return 1;

if (dn < 0) dn = -dn;

digits_integer_part = ((int)log10(dn)) + 1;
dn = dn – (int)dn;

worknumber = (int) dn;

while (worknumber % 10 != 0) {
dn = dn * 10;
worknumber = (int)dn;
}

/* Variable "worknumber" now holds the number of digits
of decimal part of the given number + 1 */

digits_decimal_part = worknumber – 1;

return digits_integer_part + digits_decimal_part;
}```

Another way of determining the number of the digits is of course converting the decimal number to string and by examining the number of characters.

## Generation of the Mandelbrot Set with computer

The Mandelbrot Set is one of the most famous fractals. This fractal carries the name of the French mathematician Benoit Mandelbrot (1924 – 2010). The first ones how implemented the Mandelbrot Set with computer where mathematicians Robert Brooks and Peter Matelski.

The mathematical definition of the Mandelbrot Set

The Mandelbrot Set is set M, where belong all the points c, to which zn is finite, when n approaches infinity, where

z0 = c

zn+1 = zn2 + c

The initial point is (0,0i). Here both z and c are complex numbers. The c is held constant and z is variable that’s value changes.

The Mandelbrot Set on the complex plane

The Mandelbrot Set is typically generated from rectangle on the complex plane from bottom left (-2.25 -1.5i) and upper right (0.75 + 1.5i). The zooming of the Mandelbrot Set is done by selecting different coordinates on this rectangle from somewhere on the border of the set. See the picture below: The set M is the black area in the picture. The other colors represent the distance from the set. In a way when you’re looking other colors than black, you’re watching infinity.

Fortunately there’s is mathematical proof, that says that is sufficient to test that is the absolute value of iterated point > 2. If the absolute value of iterated complex number is greater than 2, the iterated point is to divergence to infinity and does not belong to the set. Otherwise the point belongs to the set.

The idea of the generating the Mandelbrot Set

The recursive formula will be implemented by iterative way.

The Mandelbort set is generated to computer screen by taking each pixel point and by choosing that point as constant C (after converting this to correspond the complex plane point). When each iteration loop begins, z is first set to (0 + 0i). Next the formula z = z + c is iterated with checking if z is to divergence to infinity by calculating the absolute value of z. If the absolute value of z > 2, the point is to divergence to infinity and does not belong to the set. Otherwise the point belongs to set.

Imagine each pixel point as a point on the chosen complex plane rectangle.

Pixel’s width and height on the complex plane are calculated as follows:

```dr = (maxR - minR) / SCREEN_WIDTH
di = (maxI - minI) / SCREEN_HEIGHT```

Other thing to consider is the scale of the picture: The complex plane rectangle’s ratio must be scaled to same as screen area’s ratio.

This is calculated as follows:

The width of the rectangle wmaxR – minR
The height of the rectangle h = maxI – minI
Scaled width sW = h * (SCREEN_WIDTH / SCREEN_HEIGHT)
Difference of the scaled width and original width: diff = sW – w

Next we subtract half of the difference of the widths from the left side of the complex plane rectangle and add half of the difference of the widths to the right side of the complex plane rectangle:

minR = minR – diff / 2
maxR = maxR + diff / 2

Now the length of the complex plane rectangle is scaled to screen’s width. In practice SCREEN_WIDTH can refer in general to width of the screen’s pixel rectangle’s width.

Below is complete BlitzMax program that generates the Mandelbrot set and scales the complex plane rectangle to same ratio as the screen area’s ratio:

```Const SCREEN_WIDTH:Int = 640
Const SCREEN_HEIGHT:Int = 480
Const MAX_ITER:Int = 32

Graphics SCREEN_WIDTH, SCREEN_HEIGHT

Global minR:Float = -2.25, maxR:Float = 0.75
Global minI:Float = -1.5, maxI:Float = 1.5

Global dr:Float, di:Float

Local w:Float, h:Float, sW:Float, diff:Float

w = maxR - minR
h = maxI - minI
sW = h * (Float(SCREEN_WIDTH) / Float(SCREEN_HEIGHT))
diff = sW - w

minR = minR - diff / 2
maxR = maxR + diff / 2

dr = (maxR - minR) / SCREEN_WIDTH
di = (maxI - minI) / SCREEN_HEIGHT

For Local y:Int = 0 To SCREEN_HEIGHT - 1
For Local x:Int = 0 To SCREEN_WIDTH - 1
shade = 255 - Float(MAX_ITER - shade) / 32.0 * 255.0
Plot x,y
Next
Next

Flip
WaitKey
End

Function mandelbrot:Int(x,y)

Local iterations:Int = 0

Local cr:Float = minR + x * dr
Local ci:Float = minI + y * di
Local zr:Float = 0.0
Local zi:Float = 0.0
Local zr_temp:Float = 0.0
Local zi_temp:Float = 0.0

While (iterations < MAX_ITER)
zr_temp = zr * zr - zi * zi + cr
zi_temp = 2.0 * zr * zi + ci
zr = zr_temp
zi = zi_temp

iterations = iterations + 1
' Below is same as sqrt(zr^2 + zi^2) > 2.0
' but faster
If zr * zr + zi * zi > 4.0 Then Return iterations

Wend

Return 0

End Function
```

With greater amount of iterations it may be the case, that a point that doesn’t diverge to infinity with lower amount of iterations, diverges to infinity with greater amount of iterations. Thus, with computers in fact every generated Mandelbrot set picture is some kind of approximation of the Mandelbrot set.

Shortly about the colors

If the point c belongs to the set, the pixel is usually colored black. The other colors are calculated from the iterations. Easiest way to calculate different shades from the iterations is the following:

```shade = mandelbrot(x,y) ; The function returns the number of iterations
shade = 255 - (MAX_ITERATIONS - shade) / MAX_ITERATIONS * 255
```

This gives values 0…255 to variable shade.

Below is is picture from rectangle, that’s bottom left is (-0.22 – 0.70i) and upper right is (-0.21 – 0.69i) with different kind of coloring: Here the maximum amount of iterations is 250. In this case the number of iterations has dramatic impact to the generated picture. How colorful can the infinity be!

Mandelbrot mountain

For curiosity below is a Mandelbrot mountain generated with Python program (also my own program): The program uses the Mayavi extension, which makes it easy to do 3D visualization.

Amazon e-books on fractals I recommend especially  If you’re interested in generating Mandelbrot or Julia set mountains, I recommend the e-book below:  