The Collatz Conjecture Python Plot


No, it is not an evil plot. This chart is just another example of how easy it is to do fun things in the Python language.

Revisiting the Collatz Conjecture, I've updated the python code to plot a chart of the hailstones.  If you haven't already done so, you will need to install the Matplotlib in your python environment.  First install pip, then install matplotlib.  The -U option means upgrade dependent packages to the latest version:

python -m pip install -U pip
python -m pip install -U matplotlib

For more information, go to the matplotlib website.

Below is the updated code:


from matplotlib import pyplot as plt

def even(n):
    return n/2

def odd(n):
    return 3*n+1

n = int(input("Enter a number: "))
peak = n
count = 0
hailstones = []

while n > 1:
    count += 1
    if n % 2 == 0:
        n = even(n)
        n = odd(n)

    peak = max(peak, n)
    print (int(n))

print ("Total Hailstones = ", count)
print ("Peak = "int(peak))

# plot line with black circles
plt.plot(hailstones, '-ok')

The plot above is the result of a seed of 99.  Have fun!


Popular posts from this blog

Bookshelf: UNIX A History and a Memoir

Bookshelf Classic: The C Programming Language