Skip to content

Instantly share code, notes, and snippets.

@jdhenke
Created October 1, 2013 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdhenke/6773258 to your computer and use it in GitHub Desktop.
Save jdhenke/6773258 to your computer and use it in GitHub Desktop.
Script for generating some cool collatz plot.
from matplotlib import pyplot as plt
class Node(object):
def __init__(self, num, step, parent, children):
self.num = num
self.step = step
self.parent = parent
self.children = children
class Collatz(object):
def __init__(self):
self.memo = {}
self.memo['nums_at_step'] = {0: [1]}
self.memo['step_for_num'] = {}
def get_step(self, n):
step = 0
while n > 1:
if n % 2 == 0:
n /= 2
else:
n = (3*n) + 1
step += 1
return step
def get_nums(self, s):
if s in self.memo['nums_at_step']:
return self.memo['nums_at_step'][s]
previous_nums = self.memo['nums_at_step'][s-1]
new_nums = []
for num in previous_nums:
new_nums.append(num * 2)
if (num - 1) % 3 == 0 and (num - 1) / 3 > 1:
new_nums.append((num-1)/3)
new_nums = [x for x in set(new_nums) if x < 10000]
print s, new_nums
self.memo['nums_at_step'][s] = new_nums
return new_nums
c = Collatz()
plt.figure(1, figsize=(16, 12))
plt.subplot(111)
xmax = 100000
x = [i for i in xrange(xmax)]
y = [c.get_step(i) for i in x]
plt.scatter(x,y)
plt.ylim(ymin=0)
plt.xlim([0,xmax])
plt.savefig('c.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment