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:
#!/usr/bin/python3
from matplotlib import pyplot as plt
def even(n):
return n/2
return n/2
def odd(n):
return 3*n+1
return 3*n+1
n = int(input("Enter a number: "))
peak = n
count = 0
peak = n
count = 0
hailstones = []
hailstones.append(n)
while n > 1:
count += 1
if n % 2 == 0:
n = even(n)
count += 1
if n % 2 == 0:
n = even(n)
hailstones.append(n)
else:
n = odd(n)
n = odd(n)
hailstones.append(n)
peak = max(peak, n)
print (int(n))
print ("Total Hailstones = ", count)
print ("Peak = ", int(peak))
print ("Peak = ", int(peak))
# plot line with black circles
plt.plot(hailstones, '-ok')
plt.show()
The plot above is the result of a seed of 99. Have fun!
Comments