Skip to content

Instantly share code, notes, and snippets.

@ericjang
Created June 7, 2013 04:04
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 ericjang/5726999 to your computer and use it in GitHub Desktop.
Save ericjang/5726999 to your computer and use it in GitHub Desktop.
Hailstone Sequence (positive and negative starting numbers)
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import pdb
N_max = int(1e3) # numbers to try out
T_max = int(200) # max iterations
sequence = np.zeros((N_max, T_max), dtype=int)
# initial state
#sequence[:,0] = np.arange(1, N_max + 1) #positive numbers
sequence[:,0] = np.arange(np.floor(-N_max/2), np.floor(N_max/2)) #half neg, half pos
stopped = np.zeros((N_max, 1), dtype=int)
for i in range(1, T_max):
odds = np.mod(sequence[:,i-1], 2) == 1
evens = np.logical_not(odds)
sequence[evens, i] = sequence[evens, i-1]/2
sequence[odds,i] = sequence[odds, i-1]*3 + 1
sequence[stopped, i] = 1 #overrides for stopped numbers
stopped = sequence[:, i] == 1 #update stopped sequences
print("%d" % (i))
# Plot things
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(range(T_max), sequence.T)
#ax.set_yscale('log')
#plt.plot(range(T_max), np.arange(N_max)**2, linewidth=2.0, color='b')
plt.ylabel('Starting Numbers')
plt.xlabel('Steps')
plt.title('Positive/Negative Hailstone Sequences')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment