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. The length of the sequence chains are irregular: 15 gives a longish sequence, but next-door 16 gives a very short one. The only common thing is that apparently every sequence sooner or later goes into a 4-2-1 loop.

Now you might notice that the tiny program has a bug: it only stops if the sequence runs down to 1 or 0. Perhaps there are sequences that go into a loops of larger numbers, or perhaps there are ones that never settle into a loop but just sail higher and higher forever. In these cases the program will loop forever. However, all examples we have tried so far have ended at 4-2-1, so for now let’s keep things simple.

The tiny program can be modified to better visualize the up-and-down drift of a sequence. It will print each number on a separate line, indented proportional to the number, or rather, proportional to the logarithm of the number.

>>> from math import *

>>> def indent( num ) :
    """Return space padding sized to the given number."""
    return " " * floor(log(max(1,num),2))

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

>>> chain(11)
    11
      34
     17
      52
     26
    13
      40
     20
    10
   5
     16
    8
   4
  2
 1

>>> chain(12)
    12
   6
  3
    10
   5
     16
    8
   4
  2
 1

It’s interesting how, when you start with 11, the sequence bobs up and down a few times then arrives at 10. Numerically, 10 and 11 are neighbours, but sequentially they far apart. The sequences for 11 and 12 follow different paths until they both arrive at 10.

You might think of this tiny program’s output as an ASCII-art graph of a sequence. Perhaps the program could be expanded to draw a composite graph of many sequences overlaid. The graph might resemble a tree: down from the sky come many sequences which merge and merge until they come to a single root (4-2-1). This graph is complicated enough to draw that you’ll need a something more than the tiny program to compute the graph and something more visual than ASCII art to display it. A Python program can handle the computation, and an HTML canvas (part of the HTML5 toolkit) can handle the visuals.

The program I put together has about 250 lines of code; I won’t show the code here because of the size. The program calculates the graph then generates a file of Javascript code to plot the graph in an HTML canvas. A simple HTML page running in a browser picks up the Javascript file and executes it to reveal the graph.

Process Flow - The Python program generates a Javascript program which generates the graph image

Put together the steak and the sizzle. The Python program crunches the numbers to lay out a graph and then writes a file of Javascript code. The browser executes the Javascript code which paints the graph as an HTML Canvas image.

The program made the following image for all numbers that arrive at 1 in at most nine divide-by-two steps. Red links show divide-by-two steps; blue links show triple-and-add-one steps. (It’s easy to see that every triple-and-add-one step must be followed by a divide-by-two step.) Trace the path from right to left to follow the history of any particular sequence.Graph of 3n+1 function for shorter sequences

Below is part of the graph is for the numbers 1 to 40, along with numbers above 40 when they are in the middle of relevant sequences. The graph has ballooned thanks largely to number 27. Our friend 27 kicks off a sequence of over 100 terms that arcs from right to left, drifting slowly up and up to eventually reach 9323 before plunging back to earth – not unlike the stock prices of some high-tech companies.

Graph of 3n+1 function for numbers 1 to 40 including soaring intermediates

Here is a close-up of 27’s launch …

Graph of 3n+1 function showing sequence starting with 27

… and landing.

Graph of 3n+1 function showing final 30 numbers of sequence starting with 27

As you might expect, the 3n+1 formula has been well researched. I will stop here, but you can find more here. No one has found a number whose sequence ends in anything except the 4-2-1 loop – and all numbers up to 18 digits long have been tested. No one has proven that all sequences end this way, but neither has anyone proven that there exist any sequences with other endings.

I might add that Python is a good choice for mathematical programming. It has a lot of basics baked in (such as support for functional programming), and for advanced stuff libraries like NumPy are available.

Leave a comment