Tag Archives: python

Visualizing Math – a Small Example

Studying mathematics means investigating numbers and formulas. Getting an understanding of their abstract nature can be difficult. Computers, and the visualizing power of computer graphics, can help us to glimpse in a concrete way the natures of some of these mathematical beasts.

Lets start with a mathematical artifact that is simple to state, the so-called 3n+1 (or Collatz) sequence. Choose any integer to start the sequence. Calculate successive terms of the sequence like this:

  • If the number is even, halve it to get the next number;
  • If the number is odd, triple it then add one to get the next number.

For example, start with 10:

  • 10 is even, so halve it to get 5.
  • 5 is odd, so triple it and add 1 to get 16.
  • 16 is even, so halve it to get 8.
  • 8 is even, so halve it to get 4.
  • 4 is even, so halve it to get 2.
  • 2 is even, so halve it to get 1.
  • 1 is odd, so triple it and add 1 to get 4,
  • And we’ve gone into a loop: 1, 4, 2, 1, 4, 2.

Experiment with a few numbers and you might soon notice a few things. First, sequences seem almost completely erratic. Second, they all seem to end up in the loop 1-4-2-1 sooner or later. Third, calculating many long sequences becomes tedious.

Let’s use the computer to remove the tedium by writing a tiny program. The program is written in Python, a language which, along with its interactive shell, encourages playful, curiosity-driven programming.

>>> def chain( num ) :
    """For a given number, print its 3n+1 sequence."""
    while num > 1 :
        print( num, end=" " )
        num = num//2 if num%2 == 0 else 3*num+1
    print( num, end="\n" )

>>> chain(10)
10 5 16 8 4 2 1 

Now it gets a little easier to explore:

>>> for i in range(10,20) :
    chain(i)
10 5 16 8 4 2 1 
11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 
12 6 3 10 5 16 8 4 2 1 
13 40 20 10 5 16 8 4 2 1 
14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 
15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 
16 8 4 2 1 
17 52 26 13 40 20 10 5 16 8 4 2 1 
18 9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 
19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

You see that the sequences drift up and down but with no real pattern, like a leaf in the wind. Continue reading