Created
September 30, 2020 13:52
-
-
Save Eliran-Turgeman/fd5a409aca50986d32aac2325661e455 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
%matplotlib inline | |
def collatz(x, b=False): | |
if x % 2 == 0: | |
if b: | |
print(f'{x} is even, {x}/2 = {x/2}') | |
return x / 2 | |
else: | |
if b: | |
print(f'{x} is odd, {x}*3 + 1 = {x*3 + 1}') | |
return 3*x + 1 | |
def compute_iterations(x, b=False): | |
iter = 0 | |
y = x | |
max = y | |
while y != 1: | |
y = collatz(y, b) | |
if y > max: max = y | |
iter += 1 | |
print(f'{x} required {iter} iterations') | |
return (x, iter, max) | |
def graph_collatz(): | |
x_axis, y_axis, max_axis, m, m_x = get_data() | |
plt.plot(x_axis, y_axis, 'b.') | |
plt.plot(x_axis, [m for i in range(1, len(y_axis)+1)], 'r--') | |
plt.plot([m_x for i in range(1, len(x_axis)+1)], y_axis, 'r--') | |
plt.xlabel('Numbers') | |
plt.ylabel('Number of iterations') | |
def graph_max_collatz(): | |
x_axis, y_axis, max_axis, m, m_x = get_data() | |
plt.plot(x_axis, max_axis, 'r-') | |
plt.xlabel('Numbers') | |
plt.ylabel('Max number while getting to 1') | |
def get_data(): | |
collatz = [compute_iterations(i) for i in range(1, 100000)] | |
x_axis = [a for (a, b, c) in collatz] | |
y_axis = [b for (a, b, c) in collatz] | |
max_axis = [c for (a, b, c) in collatz] | |
m = max(y_axis) | |
print(m) | |
m_x = x_axis[y_axis.index(m)] | |
print(m_x) | |
print(max(max_axis)) | |
return x_axis, y_axis, max_axis, m, m_x | |
graph_max_collatz() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment